【问题标题】:TypeScript - Define a subset of typeTypeScript - 定义类型的子集
【发布时间】:2017-11-24 01:35:44
【问题描述】:

假设我有这样的类型:

interface IAll {
  foo: boolean,
  bar: Function,
  baz: number
}

而不是手动定义IAll 的所有可能子类型,如下所示:

interface IAll1 {
  foo: boolean,
  bar: Function,
}

interface IAll2 {
  bar: Function,
  baz: number
}

interface IAll3 {
  foo: boolean,
}

interface IAll4 {
  foo: boolean,
}

...等

然后做

type IAll = IAll1 | IAll2 | IAll3 ... etc.

TypeScript 有没有办法静态检查一个对象是否是另一个对象的子类型或子集?

这对于我们组合多个子类型或子集以形成完整类型的某些情况很有用。

【问题讨论】:

    标签: javascript node.js typescript typescript2.0


    【解决方案1】:

    您可以使用Partial<T>。这将使IAll 中的所有属性成为可选:

    type SubsetOfIAll = Partial<IAll>;
    

    【讨论】:

    • 您还可以将 Partial 用于类型和接口,例如type SubsetOfUser = Partial&lt;User&gt;
    猜你喜欢
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2020-07-31
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多