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
}
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.
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.
Union types are used when a value can be more than a single type. Such as when a property would be string or number .
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.
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; }
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