gloriaJun / til

Lessoned Learned
3 stars 0 forks source link

TS7053: How to access object attributes based on a variable in Typescript #77

Open gloriaJun opened 4 years ago

gloriaJun commented 4 years ago

Version

TypeScript 3.0

Test Scenario

interface IAddress {
  name: string;
  number: string;
  building: string;
  floor: string;
}

const initAddressData: IAddress = {
  name: '',
  number: '',
  building: '',
  floor: '',
};

  const [addressData, setAddressData] = useState<IAddress>(initAddressData);

  const handleChange = useCallback((e) => {
    const { id, value } = e.target;
    setAddressData((data) => {
      if (id in data) {
        data[id as keyof typeof data] = value;
      }

      return { ...data };
    });
  }, []);

Reference