You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
non-null assertion not working on type parameter with constraint #20974
functiontakeString(p: string){}functionfoo<Textendsstring|undefined>(param: T){takeString(param!);// error on this line}
Expected behavior:
Because of the constraint the compiler knows the type of param can only be string | undefined. Asserting the type with a non-null assertion should result in string and the code should compile without error.
If this is working as intended, I'll write a lint rule to warn about non-null assertions on type parameters.
Actual behavior:
Argument of type 'T' is not assignable to parameter of type 'string'.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
Asserting the type with a non-null assertion should result in string
We would need subtraction types to do this correctly. The correct type isn't string (because T might be instantiated with some type like "foo" | "bar"), it's T - undefined.
Oh, in case anyone happens to hit this again in the future: The new (more correct) behavior is dependent on the presence of the global NonNullable<T> type. If that's not there (because your compilation doesn't include the standard lib or includes an old one), it'll fall back to the older less-correct behavior (and consequently have the same problems). So if you still encounter this issue in TS 2.8+, double check that you've got the latest lib in your build!
Activity
RyanCavanaugh commentedon Jan 2, 2018
We would need subtraction types to do this correctly. The correct type isn't
string(becauseTmight be instantiated with some type like"foo" | "bar"), it'sT - undefined.ajafff commentedon Jan 2, 2018
Ryan Cavanaugh (@RyanCavanaugh) makes sense. So this is basically a duplicate of #4183?
RyanCavanaugh commentedon Jan 2, 2018
Not a duplicate since this case wouldn't start working automatically
no-useless-assertion: forbid non-null assertion on type parameter
ajafff commentedon Mar 6, 2018
Wesley Wigham (@weswigham) Is this fixed by #22096 or #22348?
weswigham commentedon Mar 6, 2018
#22096 should cover it.
weswigham commentedon Mar 9, 2018
Oh, in case anyone happens to hit this again in the future: The new (more correct) behavior is dependent on the presence of the global
NonNullable<T>type. If that's not there (because your compilation doesn't include the standard lib or includes an old one), it'll fall back to the older less-correct behavior (and consequently have the same problems). So if you still encounter this issue in TS 2.8+, double check that you've got the latest lib in your build!