简体   繁体   English

[Q]在TypeScript中选择object的房产

[英][Q]Select property from object in TypeScript

I am learning TypeScript in React and I have a problem with accessing property via a method argument.我在 React 中学习 TypeScript,我在通过方法参数访问属性时遇到问题。

    const [product, setProduct] = useState("electricity");
        const defaultProps = {
        price: {
              electricity: 0.51,
              gas: 4.7,
              oranges: 3.79,
            },
          };
 const selectPrice = (select: any) => {
    console.log(defaultProps.price[select]);
  };
        const handleSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setProduct(e.target.value);
      };
        <Cash
                price={selectPrice(product)}
              />
    
    <select value={product} onChange={handleSelect}>
              <option value="electricity">electricity</option>
              <option value="gas">gas</option>
              <option value="oranges">oranges</option>
            </select>

Problem is in selectPrice method.问题出在 selectPrice 方法中。 I have the error "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ electricity: number; gas: number; oranges: number; }'.ts(7053)".我有错误“元素隐式具有‘任何’类型,因为类型‘任何’的表达式不能用于索引类型‘{电:数字;气体:数字;橙子:数字;}'.ts(7053)” . I don't know how I can get access to the property of object price in object defaultProps.我不知道如何在 object defaultProps 中访问 object 价格的属性。 In guide teacher is using the javascript and it works fine.在指南中,老师使用的是 javascript,它工作正常。

You could create a type of the possible options of the select.您可以创建 select 的可能选项类型。

const selectPrice = (select: 'electricity'| 'gas' | 'oranges') => {
  console.log(defaultProps.price[select]);
};

This issue should be fixed once you change select: any to select: string .select: any更改为select: string后,此问题应该得到解决。 Since price can be indexed only using strings, when you set select: any there is a possibility that select could be a number , boolean or some other type, which will cause a runtime error, which is why Typescript is complaining.由于price只能使用字符串进行索引,因此当您设置select: any时, select 可能是一个numberboolean或其他类型,这将导致运行时错误,这就是 Typescript 抱怨的原因。

Since the benefit of using Typescript over Javascript is the stronger typing system, you should avoid using any whenever possible to take advantage of Typescript's ability to catch runtime bugs caused by mismatched types由于使用 Typescript 而不是 Javascript 的好处是更强大的类型系统,因此您应该尽可能避免使用any以利用 Typescript 捕获由不匹配类型引起的运行时错误的能力

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

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