繁体   English   中英

如何从 Typescript 中类型化的 object 的属性值生成类型?

[英]How can I generate a type from the properties values of a typed object in Typescript?

假设我有一个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 dogs | snakes ,但当然我在我的配置文件中创建新项目时会丢失打字。

我们希望限制myLibrary中的项目,以便它们必须实现MyItem ,但我们希望以保留特定项目的特定类型并且不将类型扩大到仅MyItem的方式来做到这一点。

仅通过为常量分配类型很难做到这一点。 一种常用的模式是通过标识 function 创建常量。 使用 function 我们可以使用extends语法来确保T extends MyItem[]同时保持T特定。

我必须使用as const来获取文字类别名称,所以我还必须在 function arguments 中允许readonly

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"

Typescript 游乐场链接

如果我理解正确,你想要这个: How to create enum like type in TypeScript? 然后将 MyItem 指定为

interface MyItem: {
    category: MyDogSnakeType,
    title: string
}

不要复杂化


type Categorías = 'Food' | 'categoy1' | 'cstegory2'

interface MyItem {
  category: Categories;
  title: string
}

const myLibrary: MyItem[] = [
  {
    category: "dogs",
    title: "Fuzzy quadrupeds" 
  },
  { 
    category: "snakes",
    title: "Slithery reptiles"
  },
  ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM