-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Docs: documented use of function return type conditional on argument type is impractical #1931
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
+1 spent much time on this impossible function body |
Yeah, makes sense, we should probably swap it out with:
|
I find the following works just fine: interface IdLabel {
id: number /* some fields */;
}
interface NameLabel {
name: string /* other fields */;
}
// If you pass a number, you get `IdLabel`
function createLabel(idOrName: number): IdLabel;
// If you pass a string, you get `NameLabel`
function createLabel(idOrName: string): NameLabel;
// If you pass an ambiguous type, you get an ambiguous type.
// Yes, this extra overload needs to be here, if you intend to be
// able to call it this way. Otherwise, the implementation signature
// isn't externally visible.
function createLabel(idOrName: number | string): IdLabel | NameLabel;
// The implementation has to be able to handle all of the above
// defined possibilities.
function createLabel(idOrName: number | string): IdLabel | NameLabel {
if (typeof idOrName === "number") {
return { id: idOrName };
} else {
return { name: idOrName };
}
}
const a: NameLabel = createLabel("typescript");
const b: IdLabel = createLabel(2.8);
const c: NameLabel | IdLabel = createLabel((Math.random() >= 0.5) ? "hello" : 42); |
The prime example given in official example documentation for conditional types is not implementable. const getID = function<T extends boolean>(fancy: T): T extends true ? string : number {
if(fancy) {
return 'StringID';
} else {
return 5;
}
}; but that fails to compile, even though on lines 3 and 5 where the error occurs the true/false value of 'fancy' is known at compile-time and that should permit TypeScript to figure out the expected type of the return value. #24929 remaining closed suggest this won't be fixed and it's a big sore spot when trying to implement something like the example. |
Page URL:
https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
Issue:
The example showing use of return type conditional on argument type near
TypeScript-Website/packages/documentation/copy/en/handbook-v2/Type Manipulation/Conditional Types.md
Line 82 in 3cb94f4
Recommended Fix:
I can see a few options, either:
as any
, reinstating the overloads, possibly others)The text was updated successfully, but these errors were encountered: