TypeScript - 定义类型的子集

Ale*_*lls 4 javascript node.js typescript typescript2.0

说我有这样的类型:

interface IAll {
  foo: boolean,
  bar: Function,
  baz: number
}
Run Code Online (Sandbox Code Playgroud)

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

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

interface IAll2 {
  bar: Function,
  baz: number
}

interface IAll3 {
  foo: boolean,
}

interface IAll4 {
  foo: boolean,
}
Run Code Online (Sandbox Code Playgroud)

...等等

然后做

type IAll = IAll1 | IAll2 | IAll3 ... etc.
Run Code Online (Sandbox Code Playgroud)

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

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

Sar*_*ana 14

你可以用Partial<T>.这将使所有属性成为IAll可选:

type SubsetOfIAll = Partial<IAll>;
Run Code Online (Sandbox Code Playgroud)