英文:
Typescript is not warning that a key doesn't exist on type
问题
I have the following ts definition:
interface FormValue {
fieldA: string;
fieldB: number;
}
const FIELD_NAMES: Record<string, keyof FormValue> = {
FIELD_A: 'fieldA',
FIELD_B: 'fieldB'
} as const;
I want to use FIELD_NAMES.FIELD_A
. This works fine, but there's an issue when I use something like FIELD_NAMES.X
. TypeScript doesn't warn me that X
does not exist on FIELD_NAMES
.
How can I solve this?
英文:
I have the following ts definition:
interface FormValue {
fieldA: string;
fieldB: number;
}
const FIELD_NAMES: Record<string, keyof FormValue> = {
FIELD_A: 'fieldA',
FIELD_B: 'fieldB'
} as const;
I want to the to use FIELD_NAMES.FIELD_A
, this works fine, but this has an issue, when I use something likeFIELD_NAMES.X
typescript is not warning me that X
does not exist on FIELD_NAMES
.
How can I solve this?
Here is the full playground:
答案1
得分: 3
Types and const
assertions don't go together very well. If you remove the type and use the satisfies
operator to express your constraints, you'll get the behavior you want while still maintaining type safety:
接口 FormValue {
fieldA: string;
fieldB: number;
}
const FIELD_NAMES = {
FIELD_A: 'fieldA',
FIELD_B: 'fieldB'
} as const 满足 Record<string, keyof FormValue>
const test = FIELD_NAMES.FIELD_A;
const test2 = FIELD_NAMES.X;
console.log(test);
console.log(test2);
<sup>Playground link</sup>
英文:
Types and const
assertions don't go together very well. If you remove the type and use the satisfies
operator to express your constraints, you'll get the behavior you want while still maintaining type safety:
interface FormValue {
fieldA: string;
fieldB: number;
}
const FIELD_NAMES = {
FIELD_A: 'fieldA',
FIELD_B: 'fieldB'
} as const satisfies Record<string, keyof FormValue>;
const test = FIELD_NAMES.FIELD_A;
const test2 = FIELD_NAMES.X;
console.log(test);
console.log(test2);
<sup>Playground link</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论