Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript discriminating union - parameter of discrimating property type

Tags:

typescript

I have the following definitions:

interface Dog {
  bark(): void;
  type: 'dog';
}

interface Cat {
  meow(): void;
  type: 'cat';
}

type Animal = Cat | Dog;

Now I would like to make a function that uses Animal.type as a parameter:

function useAnimalType(type: string) {}

In this example, I used string, but I really mean 'cat' | 'dog'. I realize I could write out all the possible type of Animal, but imagine a scenario when there are hundreds of animal types defined in Animal. How do I reuse the Animal.type as a parameter here?

like image 682
Deathspike Avatar asked Apr 11 '18 17:04

Deathspike


People also ask

What is discriminated unions in TypeScript?

The concept of discriminated unions is how TypeScript differentiates between those objects and does so in a way that scales extremely well, even with larger sets of objects. As such, we had to create a new ANIMAL_TYPE property on both types that holds a single literal value we can use to check against.

Can I check a type against a union type in TypeScript?

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.

How do you declare a union type variable in TypeScript?

TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type.

What operator would you use in order to specify a union type in TypeScript?

In TypeScript union types is one of the feature and it is mainly used for to define the user variable which can have multiple set and data types value like integer or number, character, string, float etc these combined data type are referred as union types and it is allowed for the variable with multiple set of data ...


1 Answers

You can retrieve the type of a field in another object type by using bracket notation. For your example, simply:

function useAnimalType(type: Animal["type"]) {}

would suffice. In such case, Animal["type"] is inferred to be "cat" | "dog".

like image 68
CRice Avatar answered Sep 29 '22 04:09

CRice