typescript属性映射中的字符串文字

时间:2018-04-23 09:24:43

标签: typescript dictionary

我似乎无法访问属性,请参阅下文:

type ValidAttributes = "FOO" | "BAR" | "BAZ";

interface MyInterface {
  attributes: {
    [s in keyof ValidAttributes]: string;
  };
}

const doSomething = (data: MyInterface): void => {
  const foo = data.attributes.FOO;
  //Error:(10, 31) TS2339: Property 'FOO' does not exist on type '{ toString: string; charAt: string; charCodeAt: string; concat: string; indexOf: string; lastInde...'.

  const bar = data.attributes["BAR"];
  //Error:(13, 15) TS7017: Element implicitly has an 'any' type because type '{ toString: string; charAt: string; charCodeAt: string; concat: string; indexOf: string; lastInde...' has no index signature.
}

我还有一个linter,可以将最后一个代码自动修改为另一种格式。如果这是唯一的方法,可以禁用它。

1 个答案:

答案 0 :(得分:1)

更改您的界面定义:

type ValidAttributes = "FOO" | "BAR" | "BAZ";

interface MyInterface {
  attributes: {
    [s in ValidAttributes]: string;
  };
}

keyof中使用ValidAttributes时,您将获得String类型的属性,因为ValidAttributes是字符串的并集。您不希望这样,您希望属性成为字符串之一,而不是字符串联合的属性,因此您只需要s in ValidAttributes,而不是s in keyof ValidAttributes