function f(x:boolean|string) { return x } f(true) // boolean | string
Why can't typescript understand that the return value is a boolean?
function f(x:boolean|string) { return typeof x === 'boolean' ? true : 'str' } f(true) // boolean | string
It can't understand this either.
Do I need to manually setup a function overload definition?
Conditional types help describe the relation between the types of inputs and outputs. When the type on the left of the extends is assignable to the one on the right, then you'll get the type in the first branch (the “true” branch); otherwise you'll get the type in the latter branch (the “false” branch).
What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .
Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.
TypeScript introduced a new type never , which indicates the values that will never occur. The never type is used when you are sure that something is never going to occur. For example, you write a function which will not return to its end point or always throws an exception.
Typescript will not infer different return types based on type guards in the function. You can however define multiple function signatures for let the compiler know the links between input parameter types and result type:
function ff(x: boolean): boolean; function ff(x: string): string; // Implementation signature, not publicly visible function ff(x: boolean | string): boolean | string { return typeof x === 'boolean' ? true : 'str' }
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