Typescript: Conditional Types / Infer
Conditional types in Typescript is like ternary operator in JavaScript, Depending on the condition, TypeScript determines which type can be assigned.
Conditional types help describe the relation between the types of inputs and outputs.
type ConditionalType = T extends U ? U : never- The extends keyword checks if every value of T can be assigned to a value of U.- If T is assignable to U, then the “true type” will be returned, U is our case.- If T is not assignable to U, then the “false type” will be returned, never, in our case
type ConditionalType = T extends U ? U : never- The extends keyword checks if every value of T can be assigned to a value of U.- If T is assignable to U, then the “true type” will be returned, U is our case.- If T is not assignable to U, then the “false type” will be returned, never, in our case
Let’s consider defining a type that exclude the falsy types and otherwise return the truthy type.
Objects are falsy if and only if they have the [[IsHTMLDDA]] internal slot.That slot only exists in document.all
and cannot be set using JavaScript.
The never keyword is often used to filter types, for example let’s declare a Filter type that accepts a union types T, and an exclude member U and if type T is assignable to the excluded member U then it returns never
Exclude is a built-in utility type in TypeScriptExclude<UnionType, ExcludedMembers>
Constructs a type by excluding fromUnionType
all union members that are assignable toExcludedMembers
Type inference in conditional types
Within the extends
clause of a conditional type, it is now possible to have infer
declarations that introduce a type variable to be inferred. Such inferred type variables may be referenced in the true branch of the conditional type. It is possible to have multiple infer
locations for the same type variable.
Let have another example
ReturnType is a built-in utility type in TypeScriptReturnType<Type>
Constructs a type consisting of the return type of functionType
.
Thanks for reading — I hope you found this article useful. Happy coding! :)