-
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 narrowing of string literal unions #9314
Labels
Duplicate
An existing issue was already created
Comments
PS: Kudos for #9163 and all the work you've put in TS. It's a trully amazing language. |
@gcnew interestingly, this works: type Easing = { val: 'ease-in' } | { val: 'ease-out' } | { val: 'ease-in-out' };
function getEasingFunction(easing: Easing): (val: number) => number {
switch (easing.val) {
case 'ease-in': return t => t * t;
case 'ease-out': return t => t * (2 - t);
case 'ease-in-out': return t => t < 0.5 ? (2 * t * t) : -1 + (4 - 2 * t) * t;
}
// `easing` should be of type `never` here
// however the actual type is `'ease-in' | 'ease-out' | 'ease-in-out'`
} |
@aluanhaddad Yeah, another workaround that doesn't change type Easing = 'ease-in' | 'ease-out' | 'ease-in-out';
function assertNever(x: never): never {
throw `Not a never ${ x }`;
}
function getEasingFunction(easing: Easing): (val: number) => number {
const x = { test: easing };
switch (x.test) {
case 'ease-in': return t => t * t;
case 'ease-out': return t => t * (2-t);
case 'ease-in-out': return t => t<0.5 ? (2*t*t) : -1+(4-2*t)*t;
default:
return assertNever(x);
}
} |
This is a duplicate of #7447. |
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
TypeScript Version:
nightly (1.9.0-dev.20160217) + strictNullChecks
Code
Expected behavior:
After an exhaustive
switch
the switched variable should be of typenever
as per #9163. Conversely, if theswitch
is not exhaustive and the return type does not accomodate forundefined
, an error should be issued.Actual behavior:
String literal union types are not narrowed thus an error is always issued.
The text was updated successfully, but these errors were encountered: