Javascript 如何从Typescript中类型化对象的属性值生成类型?
假设我有一个Javascript 如何从Typescript中类型化对象的属性值生成类型?,javascript,typescript,typescript-typings,Javascript,Typescript,Typescript Typings,假设我有一个界面,该界面描述了一个库,其中包含如下项目: 接口MyItem{ 类别:字符串, 标题:字符串 } 现在,我有了一个配置文件,其中充满了这些MyItems: const myLibrary: MyItem[] = [ { category: "dogs", title: "Fuzzy quadrupeds" }, { category: "snakes", title: &q
界面
,该界面描述了一个库,其中包含如下项目:
接口MyItem{
类别:字符串,
标题:字符串
}
现在,我有了一个配置文件,其中充满了这些MyItems:
const myLibrary: MyItem[] = [
{
category: "dogs",
title: "Fuzzy quadrupeds"
},
{
category: "snakes",
title: "Slithery reptiles"
},
...
]
现在,我想创建一个包含MyItem[]
如果我这样做:
type Category=typeof MyItem[number][“Category”]
I getstring
如果我从myLibrary
(即constmylibrary=[{…}]
)中删除键入内容并获得所需内容:
这意味着
type Category=typeof MyItem[number][“Category”]
为我提供了我想要的dogs | snakes
的联合类型,但在我的配置文件中创建新项目时,我当然会丢失键入的内容。如果我理解正确,您希望这样做:然后将MyItem指定为
interface MyItem: {
category: MyDogSnakeType,
title: string
}
我们希望限制
myLibrary
中的项目,以便它们必须实现MyItem
,但我们希望这样做的方式能够保留特定项目的特定类型,而不是将类型扩展到仅MyItem
仅通过将类型指定给常量就很难做到这一点。常用的模式是通过标识函数创建常量。通过一个函数,我们可以使用extends
语法来确保T扩展MyItem[]
,同时保持T
的特定性
我必须使用作为常量
来获取文本类别名称,因此我还必须在函数参数中允许只读
interface MyItem {
category: string,
title: string
}
const buildLibrary = <T extends readonly MyItem[]>(library: T): T => library;
const myLibrary = buildLibrary([
{
category: "dogs",
title: "Fuzzy quadrupeds"
},
{
category: "snakes",
title: "Slithery reptiles"
}
] as const);
type Categories = (typeof myLibrary)[number]['category'] // "dogs" | "snakes"
接口MyItem{
类别:字符串,
标题:字符串
}
constbuildlibrary=(库:T):T=>library;
const myLibrary=buildLibrary([
{
类别:“狗”,
标题:“模糊四足动物”
},
{
类别:“蛇”,
标题:“爬行动物”
}
]作为常量);
类型类别=(myLibrary的类型)[number]['category']/“dogs”|“snakes”
不要使事情复杂化
类型Categorías='Food'|'categoy1'|'cstegory2'
接口MyItem{
类别:类别;
标题:字符串
}
常量myLibrary:MyItem[]=[
{
类别:“狗”,
标题:“模糊四足动物”
},
{
类别:“蛇”,
标题:“爬行动物”
},
...
谢谢!我想到了枚举路线,这可能是我最终要走的路。我希望在定义库中可能存在的所有不同项目时,不必单独定义类别。
。如果有人用更好的选项回答,我会感兴趣;)是的,这也是我最后要做的!我只是希望或者一个更圆滑的解决方案:)谢谢!