简体   繁体   English

typescript 动态访问 object

[英]typescript access object dynamically

I got this error in typescript我在 typescript 中收到此错误

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 

when I try to access object property dynamically:当我尝试动态访问 object 属性时:

import React, { useState } from "react";

const cities = {
  ny: {
    label: "New York"
  },
  ld: {
    label: "London"
  }
};

export default function App() {
  const [city, setCity] = useState<string>("ny");

  console.log(cities[city].label); //what's wrong here

  return (
    <div className="App">
      hi
    </div>
  );
}

any clue how to get rid of such error?任何线索如何摆脱这种错误?

You say that cities have only two keys when you declare it: "ny" and "ld" but then you allow any city to be a key of your cities element.您说城市在声明时只有两个键:“ny”和“ld”,但是您允许任何城市成为您的城市元素的键。

Changing:改变:

useState<string>

to

useState<"ny" | "ld">("ny")

should solve your issue.应该可以解决您的问题。

If you want to allow more city you could also go with this approach:如果你想允许更多的城市,你也可以用这种方法 go :

type City = {
  [key: string]: {
    label: string;
  };
};

const cities: City = {
  ny: {
    label: "New York",
  },
  ld: {
    label: "London",
  },
};

and keep your useState.并保持你的 useState。

Finally you could dynamically generate the possible keys based on your cities const using:最后,您可以使用以下命令根据您的城市 const 动态生成可能的密钥:

const [city, setCity] = useState<keyof typeof cities>("ny");

You can't use string type to access properties on your object without index type.您不能使用string类型来访问没有索引类型的 object 上的属性。 But if you use useState<keyof typeof cities>("ny");但是如果你使用useState<keyof typeof cities>("ny"); that will pick up that it's not just a string but specific string in an object("ny" and "ld" in this case).这将表明它不仅仅是一个字符串,而是对象中的特定字符串(在这种情况下为“ny”和“ld”)。

You can also play around with enum and index types if you need to:)如果需要,您还可以使用enum和索引类型:)

cities is untyped, and cities.ny too, it's literally "implicitly has an 'any' type". cities是无类型的, cities.ny也是,它的字面意思是“隐式具有'任何'类型”。 To get rid of this error you should provide type to your variable, for example you can do:为了摆脱这个错误,你应该为你的变量提供类型,例如你可以这样做:

interface City {
    label: string
}

const cities: {[name: string]: City} = {
    ny: {
        label: "New York"
    },
    ld: {
        label: "London"
    }
};

And compiler will know the type of label .编译器会知道label的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM