Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 375
Alexander Mills Avatar asked Jun 21 '17 08:06

Alexander Mills


People also ask

How do you define a type in TypeScript?

Custom Type Syntax In TypeScript, the syntax for creating custom types is to use the type keyword followed by the type name and then an assignment to a {} block with the type properties.

How do you define object of objects type in TypeScript?

In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.

Is it possible to combine types in TS?

TypeScript allows us to not only create individual types, but combine them to create more powerful use cases and completeness. There's a concept called “Intersection Types” in TypeScript that essentially allows us to combine multiple types.


1 Answers

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

type SubsetOfIAll = Partial<IAll>;
like image 196
Saravana Avatar answered Sep 17 '22 13:09

Saravana