繁体   English   中英

TypeScript - 定义类型的子集

[英]TypeScript - Define a subset of type

说我有这样的类型:

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静态检查对象是否是另一个的子类型或子集?

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

您可以使用Partial<T> 这将使IAll所有属性IAll可选:

type SubsetOfIAll = Partial<IAll>;

暂无
暂无

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

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