-
Notifications
You must be signed in to change notification settings - Fork 12.8k
narrowing doesn't work for literal strings in switch when united with unconstrained string #10417
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
Side question: what was your intent declaring something |
example1: DB guys introduced a new possible value to a set of well-known values, without letting anyone know, this new case has to be treated separately as a failure/default case/you name it example2: this one is lengthy, gradual open-ended narrowing via composing resolving functions
type One = 'a' | 'b';
interface ViaOne<r> {
caseOfA: (value: 'a') => r;
caseOfB: (value: 'b') => r;
}
function viaOne<r>(kind: One | string, via: ViaOne<r>) : Optional<r> {
switch (kind) {
case 'a': return someFrom(via.caseOfA(kind));
case 'b': return someFrom(via.caseOfB(kind));
default: return none;
}
}
type Another = 'c' | 'd';
interface ViaAnother<r> {
caseOfC: (value: 'c') => r;
caseOfD: (value: 'd') => r;
}
function viaAnother<r>(kind: Another | string, via: ViaAnother<r>): Optional<r> {
switch (kind) {
case 'c': return someFrom(via.caseOfA(kind));
case 'd': return someFrom(via.caseOfB(kind));
default: return none;
}
}
type CrazyStuff = One | Another;
interface ViaCrazyStuff<r> extends ViaOne<r>, ViaAnother<r> {}
function viaCrazyStuff<r>(value: CrazyStuff, via: ViaCrazyStuff<r>): Optional<r> {
const tryOne = viaOne(value, via);
if (isSome(tryOne)) {
return tryOne;
} else {
return viaAnother(value, via);
}
} |
This is working as intended, so I'm changing the label to a suggestion. We currently only narrow in a |
fyi, there is a workaround using function useA(value: 'a'): void { }
function useB(value: 'b'): void { }
function useSomethingElse(value: string): void { }
function test<c extends string>(kind: 'a' | 'b' | c) {
switch (kind) {
case 'a': useA(kind); break;
case 'b': useB(kind); break;
default: useSomethingElse(kind);
}
} |
@ahejlsberg why wouldn't we narrow whenever a literal value matches a literal in a union? |
nightly build, August 18, 2016
The text was updated successfully, but these errors were encountered: