最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeScript - Define a subset of type - Stack Overflow

programmeradmin1浏览0评论

Say I have a type like so:

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

instead of manually defining all the possible subtypes of IAll, like so:

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

interface IAll2 {
  bar: Function,
  baz: number
}

interface IAll3 {
  foo: boolean,
}

interface IAll4 {
  foo: boolean,
}

...etc

and then doing

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

Is there a way for TypeScript to statically check whether an object is a subtype or subset of another?

This is useful for some cases where we combine several subtypes or subsets to form a full type.

Say I have a type like so:

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

instead of manually defining all the possible subtypes of IAll, like so:

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

interface IAll2 {
  bar: Function,
  baz: number
}

interface IAll3 {
  foo: boolean,
}

interface IAll4 {
  foo: boolean,
}

...etc

and then doing

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

Is there a way for TypeScript to statically check whether an object is a subtype or subset of another?

This is useful for some cases where we combine several subtypes or subsets to form a full type.

Share Improve this question edited Jun 21, 2017 at 18:31 Alexander Mills asked Jun 21, 2017 at 8:50 Alexander MillsAlexander Mills 100k165 gold badges531 silver badges908 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

You can use Partial<T>. This will make all the properties in IAll optional:

type SubsetOfIAll = Partial<IAll>;
发布评论

评论列表(0)

  1. 暂无评论