简体   繁体   中英

[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.

    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. 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)". I don't know how I can get access to the property of object price in object defaultProps. In guide teacher is using the javascript and it works fine.

You could create a type of the possible options of the 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 . 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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