元素隐式具有“any”类型。在“User1”类型上找不到带有“string”类型参数的索引签名

问题描述 投票:0回答:1

我尝试在打字稿中使用计算属性。但低于错误。

checkParameter 是随机的,将在运行时决定。

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User1'.
  No index signature with a parameter of type 'string' was found on type 'User1'

代码

type User1 = {
  name: string;
  age: number;
  address: string;
};

const user1: User1 = {
  name: "user1",
  age: 23,
  address: "address",
};

let checkParameter: string | number = "name";
console.log(user1[checkParameter]); //error occuring here

checkParameter = "age";
console.log(user1[checkParameter]); //error occuring here

checkParameter = "address";
console.log(user1[checkParameter]); //error occuring here

我期待着,无错误执行。

javascript typescript javascript-objects
1个回答
0
投票

您可以添加

[key: string]: string
来指定类型 User1 具有带有
string

类型键的属性
type User1  = {
   [key: string]: any;
   name: string;
   age: number;
   address: string;
};

const user1: User1 = {
   name: "user1",
   age: 23,
   address: "address",
};

let checkParameter: string | number = "name";
console.log(user1[checkParameter]);

由于

checkParameter
有两种类型
string | number
并且它指的是一个键,如果 User1 类型将有一个类型为 number 的键,请将此类型添加到键中:

type User1  = {
   [key: string | number]: any
   name: string;
   age: number;
   address: string;
};
© www.soinside.com 2019 - 2024. All rights reserved.