Javascript 如何在typescript中使用文字字符串类型键 type水果='apple'|'banana'|'berry'; 类型fructsseeds=记录; 常量种子:水果种子={苹果种子:3,香蕉种子:2,浆果种子:6}; const myApple:水果=‘苹果’; const myappleeds=mySeeds[`${myApple}Seed`]; //元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型为“fruitsSeeds”。 //在类型“水果种子”ts(7053)上未找到参数类型为“字符串”的索引签名

Javascript 如何在typescript中使用文字字符串类型键 type水果='apple'|'banana'|'berry'; 类型fructsseeds=记录; 常量种子:水果种子={苹果种子:3,香蕉种子:2,浆果种子:6}; const myApple:水果=‘苹果’; const myappleeds=mySeeds[`${myApple}Seed`]; //元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型为“fruitsSeeds”。 //在类型“水果种子”ts(7053)上未找到参数类型为“字符串”的索引签名,javascript,typescript,Javascript,Typescript,我试图使用紧凑型接口。 但是这里有一些问题需要使用文本键来获取属性。 有没有更好的方法不将文本类型更改为字符串?const myappleeds=myeeds[`${myApple}Seed`as const]我相信你可以写它是一个答案谢谢虫族!这对我很合适 type fruits = 'apple' | 'banana' | 'berry'; type fruitsSeeds = Record<`${fruits}Seed`, number>; const mySeed

我试图使用紧凑型接口。 但是这里有一些问题需要使用文本键来获取属性。
有没有更好的方法不将文本类型更改为字符串?

const myappleeds=myeeds[`${myApple}Seed`as const]我相信你可以写它是一个答案谢谢虫族!这对我很合适
  type fruits = 'apple' | 'banana' | 'berry';
  type fruitsSeeds = Record<`${fruits}Seed`, number>;
  const mySeeds: fruitsSeeds = { appleSeed: 3, bananaSeed: 2, berrySeed: 6 };
  const myApple: fruits = 'apple';

  const myAppleSeeds = mySeeds[`${myApple}Seed`];
  //Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'fruitsSeeds'.
  // No index signature with a parameter of type 'string' was found on type 'fruitsSeeds'.ts(7053)