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?
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.
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.
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.
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 ...
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With