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
Search Terms:
typescript return type based on parameter Code
typeStringOrNull<BextendsBoolean>=Bextendstrue ? string : (string|null)typeStringNotNull=StringOrNull<true>functionfoo<Bextendsboolean>(returnString: B): StringOrNull<B>{if(returnString){return''asStringNotNull// type error: "Type 'string' is not assignable to type 'StringOrNull<B>'"}else{returnnull}}
Expected behavior:
Typecast should be valid, with the return type of foo being:
string when returnString is passed as true
string | null when returnString is passed as false
Actual behavior:
Cast cannot succeed, and return type is not dynamic based on the boolean passed to foo
StringNotNull expressly passes true to your helper which expressly resolves to just string (it has no generics left so is no longer actually a conditional; it's already "executed"). You should probably just cast to StringOrNull<typeof returnString> to retain the dependence on B instead.
StringNotNull expressly passes true to your helper which expressly resolves to just string (it has no generics left so is no longer actually a conditional; it's already "executed"). You should probably just cast to StringOrNull<typeof returnString> to retain the dependence on B instead.
Casting to StringOrNull<typeof returnString> will still result in the same type error that 'string' is not assignable to type 'StringOrNull<B>'. I was, however, able to make the cast succeed by casting to StringOrNull<B>, though that route doesn't fix the root issue that the return type of foo will then always be string, independent of the passed boolean.
TypeScript Version: 2.9.2
Search Terms:
typescript return type based on parameter
Code
Expected behavior:
Typecast should be valid, with the return type of
foo
being:string
whenreturnString
is passed astrue
string | null
whenreturnString
is passed as falseActual behavior:
Cast cannot succeed, and return type is not dynamic based on the boolean passed to
foo
Playground Link:
https://www.typescriptlang.org/play/#src=type%20StringOrNull%3CB%20extends%20Boolean%3E%20%3D%20B%20extends%20true%20%3F%20string%20%3A%20(string%20%7C%20null)%0D%0Atype%20StringNotNull%20%3D%20StringOrNull%3Ctrue%3E%0D%0A%0D%0Afunction%20foo%3CB%20extends%20boolean%3E(throwError%3A%20B)%3A%20StringOrNull%3CB%3E%20%7B%0D%0A%20%20if%20(throwError)%20%7B%0D%0A%20%20%20%20throw%20Error()%0D%0A%20%20%7D%0D%0A%20%20return%20''%20as%20StringNotNull%0D%0A%7D
Related Issues:
The text was updated successfully, but these errors were encountered: