Typescript没有警告类型上不存在的键。

huangapple go评论60阅读模式
英文:

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&lt;string, keyof FormValue&gt; = {
  FIELD_A: &#39;fieldA&#39;,
  FIELD_B: &#39;fieldB&#39;
} 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:

https://www.typescriptlang.org/play?ssl=6&amp;ssc=51&amp;pln=6&amp;pc=21#code/JYOwLgpgTgZghgYwgAgGIHsoFsBqcA2ArigN4CwAUMsjMBPgCYCCAXMgM5hSgDmA3JWq16DAEJsQhLACNoAigF9KlBOhCc0ASQCiAGQAiAfQByTALLaAymwBKEVVAYAeTtxA8ANMgDWEAJ7oMGiYuATEAHzIALzI5FRaekasyADkwoxMKR6CCQaG4qnpYimUCshw7Miq6mDyKmoakBoxqDp5phaWAHStiYZM8tWNEJwATNG5Rh1WXQAafMgA9IvIIOjI0FCYyAD8yhRD6PgQXfjoPAAUTWAAlIMNRydnl9ejd0A

答案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: &#39;fieldA&#39;,
  FIELD_B: &#39;fieldB&#39;
} as const satisfies Record&lt;string, keyof FormValue&gt;;

const test = FIELD_NAMES.FIELD_A;
const test2 = FIELD_NAMES.X;

console.log(test);
console.log(test2);

<sup>Playground link</sup>

huangapple
  • 本文由 发表于 2023年4月13日 17:56:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定