10 Matching Annotations
  1. Oct 2019
    1. 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.
    1. Based on examples given in https://github.com/Microsoft/TypeScript/issues/29049

      Specific link: http://www.typescriptlang.org/play/#code/LAKAZgrgdgxgLgSwPZQARigRgDwBVUCmAHnAVACYDOqlcATglAOYB8AFEQFyq4CU3+AN6hUqOgTgQ6aAEQALAgBtFSVAHckdReQCEM1AHoDAQ2q4A3KAC+oOAE8ADgVQBleseaoAvKnkIZoDAotDT0jEzcbnQeTN6+cv6BwUiKBAB0KkxsGJhstAzMvLygoJCwiCjoUABMeIQkZFSoABK4ALIAMgCiqQC2ZHDsSABGAFYC-DyowiCi4pLSqFAEai3tHQAiCMaZPQT9UHBsRaimPJYgNiCl0PDIaBgAzHXEpBTUw0gpBB5DYwJxMA7SgEXjTaw3cr3KoAFheDXeqE+31+bBG4x4kyEIkMBnmUjQ6Jx+MWQMUIIhIHsTh4dAgBFwjmcPno9IuQSgIWRilwdIIAj5jJpLL57OSqQySCyGBhbG5vPpRRKIDIEF6qC64NmolQAA0ADSoACahoAWtYgA

      and: http://www.typescriptlang.org/play/#code/LAKAZgrgdgxgLgSwPZQARigRgDwBVUCmAHnAVACYDOqlcATglAOYB8AFEQFyq4CU3+AN6hUqOgTgQ6aAEQALAgBtFSVAHckdReQCEM1AHoDAQ2q4A3KAC+oOAE8ADgVQBleseaoAvKnnH9AD6+csbKSDKgMCi0NO7M3G50Hkzewf6R0UiKBAB0KkxsGJhstEnMvLygoJCwiCjoUABMeIQkZFSoABK4ALIAMgCi2QC2ZHDsSABGAFYC-DyowiCi4pLSqFAEal29fQAiCKFITEMEo1BwbBWopjyWIDYg1dDwyGgYAMwtxKQU1JNILIEDwTGYCVJgUKUAi8RbWZ61N4NAAs3zaf1QAKBILYU1mPHmQhEhgMqykaDxxLJ60himh8JA9icPDoEAIuEczh89DZ9yiUBiWMUuFZBAEoo5zO5or5mWyeWOhSgyLYQpFbIqVRAZAgw1QAzhy1EqAAGgAaVAATQtAC1rEA

    1. 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.