【发布时间】:2021-03-13 22:52:53
【问题描述】:
假设我有一个 interface 描述了一个库,其中的项目看起来像这样:
interface MyItem {
category: string,
title: string
}
现在我有一个包含这些 MyItems 的配置文件:
const myLibrary: MyItem[] = [
{
category: "dogs",
title: "Fuzzy quadrupeds"
},
{
category: "snakes",
title: "Slithery reptiles"
},
...
]
现在,我想创建一个包含MyItem[] 中所有category 的类型
如果我这样做:
type Category = typeof MyItem[number]["category"]我得到string。
如果我从myLibrary(即const myLibrary = [ {...} ])中删除输入并得到我想要的:
这意味着 type Category = typeof MyItem[number]["category"] 为我提供了我想要的 dogs | snakes 联合类型,但当然在我的配置文件中创建新项目时我会丢失类型。
【问题讨论】:
标签: javascript typescript typescript-typings