10 Matching Annotations
- Oct 2019
-
stackoverflow.com stackoverflow.com
Tags
Annotators
URL
-
-
stackoverflow.com stackoverflow.com
-
stackoverflow.com stackoverflow.com
-
Let's make the example even easier. function convertDate<T extends string | undefined>(isoDate?: string): T { return undefined } 'undefined' is assignable to the constraint of type 'T' Means: What you return in the function (undefined), matches the constraints of your generic type parameter T (extends string | undefined). , but 'T' could be instantiated with a different subtype of constraint 'string | undefined'. Means: TypeScript does not consider that as safe. What if you defined your function like this at compile time: // expects string return type according to generics // but you return undefined in function body const res = convertDate<string>("2019-08-16T16:48:33Z") Then according to your signature, you expect the return type to be string. But at runtime that is not the case! This discrepancy that T can be instantiated with a different subtype (here string) than you return in the function (undefined) is expressed with the TypeScript error.
-
-
www.typescriptlang.org www.typescriptlang.org
-
Based on examples given in https://github.com/Microsoft/TypeScript/issues/29049
-
-
stackoverflow.com stackoverflow.com
-
Both of the below are valid as far as T extends (...args: any[]) => any goes logFn((a, b) => a + b) logFn((a, b, c) => c) But if you refer back to the example I gave, the inner definition as: return (a, b) => fn(a, b); So option 2. will throw an error here, which is why typescript is warning you about it.
-
-
github.com github.com
-
In the body of the function you have no control over the instantiation by the calling context, so we have to treat things of type T as opaque boxes and say you can't assign to it. A common mistake or misunderstanding was to constraint a type parameter and then assign to its constraint, for example: function f<T extends boolean>(x: T) { x = true; } f<false>(false); This is still incorrect because the constraint only restricts the upper bound, it does not tell you how precise T may really be.
-
-
stackoverflow.com stackoverflow.com
-
P can't be assigned {}, since the Generic Type P can be a more defined (or restricted) type.
-
-
stackoverflow.com stackoverflow.com
-
you can have a Type that is more specific than a boolean like this
-
-
github.com github.com
-
The value 10 is assignable to the constraint of T, but it is not assignable to this particular instantiation of T. If there was no error I would passing 10 where 3 is expected!
-