简体   繁体   中英

TypeScript - Define a subset of 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.

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

type SubsetOfIAll = Partial<IAll>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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