网站搜索

联合类型 - TypeScript 并不要求所有索引属性


我有以下代码:

type AZ = 'a'|'b'|'c'|'d'| ... |'z'; // union of many types

type Mapping = {
  [K in AZ]: string;
}

const obj: Mapping = { // error, missing properties 'c', 'd', etc.
  a: '',
  b: ''
};

这让我可以将 obj 的属性限制为仅匹配联合类型的那些,但它强制要求我列出它们的全部。如果我改成这样做:

type Mapping = {
  [K in AZ]?: string;
}

现在我不必提供每个 prop,但生成的 prop 类型包含 undefined。我如何才能表达我只想提供 AZ 中的一些键,但如果提供了,它们不应该是 undefined?换句话说,我想要:

const obj: Mapping = { // ok
  a: '',  // checks 'a' as string
  b: ''   // checks 'b' as string
  bad: '' // error 'bad' not in AZ
  // no additional props needed
};

... 无需使用像 obj[prop]! 这样的断言。

附注:这是否与 https://github.com/microsoft/TypeScript/issues/13195 有关?