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
// Your code hereinterfaceMyInterface{id: stringnullable: string|null}functionfailedInference(){constinput: MyInterface={id: 'id',nullable: 'non-null'}if(!input.nullable){thrownewError()}returninput}consttestFailedInference=failedInference()// This shouldn't fail because the function validates that the nullable field is non-nullable but it failsletnullableLength=testFailedInference.nullable.length
🙁 Actual behavior
The type of the returned testFailedInference.nullable is still string | null and this is wrong because I already validated it to be non nullable in the function and typescript is inferring function return type
🙂 Expected behavior
The type of the returned testFailedInference.nullable is just string and not nullable.
Additional information about the issue
Implementing it in a form-factor like this works
functionsuccessInference(){constinput: MyInterface={id: 'id',nullable: 'non-null'}if(!input.nullable){thrownewError()}return{
...input,nullable: input.nullable}}consttestSuccessInference=successInference()// This succeeds after manually specifying in the function returnletnullable2Length=testSuccessInference.nullable.length
The text was updated successfully, but these errors were encountered:
This is working as intended. Checks within functions do not propagate to outside the function, unless you're writing an explicit type guard or assertion function. Your function returns a MyInterface, and the nullable property can be null.
🔎 Search Terms
"null checking", "function inference", "null check inference", "function null check"
🕗 Version & Regression Information
⏯ Playground Link
https://www.typescriptlang.org/play/?#code/JYOwLgpgTgZghgYwgAgLIE8CS5rycgbwChllgATALmQGcwpQBzE5EAVwBsO4AjDianQYhGyAD6tOHIgF8iRGGxAIwwAPYhk8YP3LYY0CMogAKAJSEWCDXTIgADmzDUM2SLEQoAvJdKkK1ADkFIEANCyk7Fy8-EEgGgC0URyBLHL+MMgmAISgjmAAdMkxEBbEfshgABZQagDurBANAKJQtVDmafKkUBBgbFCaeU6y8tYgtpB0AGJwOhB6IAa9xsg+2rr6hsadAPS7yAAqVcA0tFVqnOQggWBacxzIPBAIcGw0KNUoisqqGsgANzgHAocCmlSqYIhKGKfG+wAgHHIZDO8RASSkJSeTjIdw2NCI-DusP4ABkjIxqmtKhAZg8FlsVkgipi4QV+CJqkA
💻 Code
🙁 Actual behavior
The type of the returned
testFailedInference.nullable
is stillstring | null
and this is wrong because I already validated it to be non nullable in the function and typescript is inferring function return type🙂 Expected behavior
The type of the returned
testFailedInference.nullable
is juststring
and not nullable.Additional information about the issue
Implementing it in a form-factor like this works
The text was updated successfully, but these errors were encountered: