Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a type from a tagged union type in typescript?

Say there is already a type defined as this:

export type Item = {
  type: 'text',
  content: string
} | {
  type: 'link',
  url: string
}

Is it possible to extract the link part from the type Item? I mean, is it possible to define a type ExtractTypeFrom:

type LinkItem = ExtractType<Item, 'type', 'link'>

And the LinkItem will be:

{
  type: 'link',
  url: string
}
like image 821
Freewind Avatar asked Oct 23 '18 07:10

Freewind


People also ask

How do you handle a union type in TypeScript?

TypeScript Union Type Narrowing To narrow a variable to a specific type, implement a type guard. Use the typeof operator with the variable name and compare it with the type you expect for the variable.

How check string is member of union type?

To check if a string is in a union type:Create a reusable function that takes a string as a parameter. Add the values of the union type of an array. Use the includes() method to check if the string is contained in the array.

When would one use a union type in TypeScript?

Union types are used when a value can be more than a single type. Such as when a property would be string or number .

Does not exist on type Union TypeScript?

The "property does not exist on type union" error occurs when we try to access a property that is not present on every object in the union type. To solve the error, use a type guard to ensure the property exists on the object before accessing it.


1 Answers

Yes it is possible you are very close, you can use the predefined Extract conditional type. You can will need to pass in, as the second argument, a type that can be a base type for the type you are seeking:

type LinkItem = Extract<Item, { type: 'link' }> // will be  { type: "link"; url: string; }
like image 182
Titian Cernicova-Dragomir Avatar answered Sep 18 '22 15:09

Titian Cernicova-Dragomir