-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Mapped type used with keyof
not narrowing
#36050
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
I'm not sure if it is relevant. TypeScript 3.7.4 (also Nightly Build) infers my variable as |
FYI this isn't a mapped type. The function could be written as function test(value: Example[keyof Example]): void {
if (value === null) {
onlyNull(value);
return;
}
onlyBoolean(value);
} without loss of generality; if you have a more complete example that requires The narrowing here can't apply because |
Consider this more complex example: const I18N_EXAMPLE_WITHOUT_DATA_KEY = `Example.WithoutData`;
const I18N_EXAMPLE_WITH_DATA_KEY = `Example.WithData`
type I18nKey = typeof I18N_EXAMPLE_WITHOUT_DATA_KEY | typeof I18N_EXAMPLE_WITH_DATA_KEY;
interface I18nDataMap {
[I18N_EXAMPLE_WITHOUT_DATA_KEY]: null,
[I18N_EXAMPLE_WITH_DATA_KEY]: { count: number },
}
function onlyNull(arg: null): void {
// do nothing
}
function interpolate<K extends I18nKey>(key: K, data: I18nDataMap[K]): string {
const value = `Use ${key} to fetch value from somewhere`;
if (data === null) {
// Argument of type 'I18nDataMap[K]' is not assignable to
// parameter of type 'null'.
onlyNull(data);
return value;
}
const result = `Some interpolated value`;
return result;
} In the above example, |
Apologies for digging this up, but I think I'm running into a similar (or the same) issue. Given this code (playground link): function exhaustiveCheck(check: never): never {
throw new Error('ERROR!');
}
interface Settings {
settingA: boolean;
settingB: string;
settingC: number;
}
function getValue<T extends keyof Settings>(key: T): Settings[T] {
if (key === 'settingA') {
return true;
} else if (key === 'settingB') {
return 'test';
} else if (key === 'settingC') {
return 5;
} else if (key === '') {
exhaustiveCheck(key);
}
} I would expect both the Am I completely missing something here, or is this simply not possible? I have similar approaches in other places that do seem to work fine. |
TypeScript Version: Nightly
Search Terms:
computed type
mapped type narrow
keyof narrow type
type index narrow
Expected behavior:
No errors.
Actual behavior:
The type for
value
is not being narrowed on either side of theif
statement.Related Issues:
Code
Output
Compiler Options
Playground Link: Provided
The text was updated successfully, but these errors were encountered: