【问题标题】:TypeScript Element implicitly has an 'any'TypeScript 元素隐含一个“任何”
【发布时间】:2022-01-23 06:32:36
【问题描述】:

我对 TypeScript 有一些问题。我正在尝试将一些来自父组件的值转换为子组件。 Parent 发送的值可以是 EN、FR 或 NL,而我应该将这些值转换为数字,所以我这样做了:

const transform_translation = {
      'EN': 1,
      'FR': 2,
      'NL': 3
    };

但是当我试图获得像 transform_translation[props.language] 这样的价值时,它会说;

S7053:元素隐式具有“任何”类型,因为类型的表达式 'any' 不能用于索引类型 '{ EN: number; FR:数字;荷兰:

道具:

props: {
    language: {
      type: String,
      default: ['EN', 'NL', 'FR'],
      required: true
    },
.
.
.
}

那我应该如何定义它们呢?顺便说一句,我是第一次与 TS 合作。

号码; }'。

【问题讨论】:

  • 你能显示道具的类型定义吗?
  • 语言:{类型:字符串,默认:['EN','NL','FR'],必填:true},
  • 你确定这是道具上的类型吗?比如,你能告诉我你在哪里定义组件吗?对于函数组件,它看起来类似于const MyComponent: FC<MyComponentProps> = (props) => {const MyComponent = (props: MyComponentProps) => ,加上MyComponentProps 的相应定义

标签: javascript typescript


【解决方案1】:

您应该告诉 ts 您传递的不仅仅是字符串,而是仅限于您拥有的语言的可用键:

const transform_translation = {
  EN: 1,
  FR: 2,
  NL: 3
};

// create type out of valid keys of object
type Language = keyof typeof transform_translation;

const getLanguageNum = (lang: Language) => transform_translation[lang];

console.log(getLanguageNum("EN")); // 1

【讨论】:

    【解决方案2】:

    我会像这样创建一个枚举或键入密钥。然后在访问它时,您可以将密钥转换为如下类型

    type ITransformTranslationKey = 'EN' | 'FR' | 'NL';
    const transform_translation: Record<ITransformTranslationKey, number> = {
          'EN': 1,
          'FR': 2,
          'NL': 3
        };
    
    const someVar: ITransformTranslationKey = 'E' + 'N'; // you can define the type here
    transform_translation[someVar as ITransformTranslationKey] // or here
    

    【讨论】:

    • 结果是一样的,因为 props.language 出了问题..
    • 你什么时候得到这个问题?访问 obj 时?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2017-07-22
    • 2020-05-29
    • 1970-01-01
    • 2023-03-22
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多