-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Type not narrowed by checking the value of a template literal type #53887
Comments
Your type First the part Then the part That means your final type for This is how I would write it: type Modified<T extends A | B> = { [P in keyof T]: P extends "type" ? `prefix-${T[P]}` : T[P] }; Not sure if there's a more elegant way to write this type, but this works as you expect. You could also write it like this. The important part is the conditional type, resulting in distributive behaviour: type Modified<T extends A | B> = T extends any ? Omit<T, "type"> & { type: `prefix-${T["type"]}` } : never |
That's an excellent observation. The fact that Thanks for your suggestions, however my example is a bit more complicated in a way that mixes with your suggested solutions n. 2 - I was originally doing it like this: import type { Node } from "postcss";
type Modified<PostCSSNode extends Node> =
Omit<PostCSSNode, "type"> & {
type: `SvelteStyle-${PostCSSNode["type"]}`;
}; However, this works: type Modified<PostCSSNode extends Node> =
PostCSSNode extends any
? Omit<PostCSSNode, "type"> & {
type: `SvelteStyle-${PostCSSNode["type"]}`;
}
: never; I'm leaving this here for posterity, however, I have absolutely no idea why this changes anything, since I presumed the original generic would do basically the same thing... |
It's been implemented that way, and changing it now would be a huge breaking change. It's unlikely to be changed: #53696 (comment)
It changes because you're using a conditional type, causing your type to be evaluated distributive. Distributiveness matters when you pass in a union type. A quick example type
See also the documentation: Distributive Conditional Types This matters a lot with Hope my explanation is somewhat understandable. |
Uff, thanks for your patience and great explanations. I see, yeah, changing something like Every time I think I understand TS reasonably well, a thing like distributive conditional types comes along and convinces me otherwise :D |
Bug Report
π Search Terms
template literal, string interpolation, type narrowing
π Version & Regression Information
β― Playground Link
I have a hard time describing this issue, the playground link will explain it better I think:
Playground Link
I would expect
fn2
to work in the same way thatfn1
doesπ» Code
π Actual behavior
Errors in the
console.log
s infn2
π Expected behavior
No errors, same as in
fn1
.The text was updated successfully, but these errors were encountered: