Home > Enterprise >  [Q]Select property from object in TypeScript
[Q]Select property from object in TypeScript

Time:02-11

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.

CodePudding user response:

You could create a type of the possible options of the select.

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

CodePudding user response:

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

  • Related