Conditional types documentation missing information crucial for their usage.
See original GitHub issueBug Report
Documentation for conditional types is missing very important information about limitations. If someone wishes to use them frustration ensues because it is not working as one would expect. Documentation uses throw “unimplemented”; and gives no warnings about issues you could run into when actually making an implementation.
After several hours of trying and searching and already strongly believing it is a bug, I found that it is Design limitation - https://github.com/microsoft/TypeScript/issues/22735
🔎 Search Terms
conditional types not working, TS2322, conditional types, broken conditional types
Problematic code
- Taken straight from documentation with simple implementation added + with workaround.
- the same on codesandbox: https://codesandbox.io/s/si8kv
interface IdLabel {
id: number /* some fields */;
}
interface NameLabel {
name: string /* other fields */;
}
type NameOrId<T extends number | string> = T extends number
? IdLabel
: NameLabel;
function createLabelBad<T extends number | string>(idOrName: T): NameOrId<T> {
if (typeof idOrName === 'string') {
return {name: idOrName}; // TS2322
}
return {id: idOrName}; // TS2322
}
function createLabelGood<T extends number | string>(idOrName: T): NameOrId<T> {
if (typeof idOrName === 'string') {
const nameLabel: NameLabel = {name: idOrName};
return nameLabel as any;
}
const idLabel: IdLabel = {id: idOrName};
return idLabel as any;
}
🙁 Actual behavior
Very important information is omitted from documentation. This causes unnecessary frustration and headaches and lost time.
🙂 Expected behavior
Very important information about limitations of conditional types is mentioned possibly with some workarounds presented instead of throw “unimplemented”;
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:5 (1 by maintainers)
Top GitHub Comments
I just came here to write the same thing and found this issue!
Since it is a known limitation / bug, the documentation should at least mention the recommended workaround to use and actually provide an implementation for the
createLabel
method instead of a simple error throwingJust for reference except for @psznm 's answer where you type the return values of the function, you can also use the conditional typed function as an overload and write the function without any return type (inferred). This will also work. Specifically:
TSPlayground link
Thank you! The workaround from that issue is the thing I would love to see in the documentation! With that information I am now able to make it much cleaner and safer.