Home > Software design >  How to cast string type to one of object types in Typescript?
How to cast string type to one of object types in Typescript?

Time:10-06

I have the following interface saying:

export interface Address_findUserAddress {
  addressCity: string | null;
  addressCountry: string | null;
  addressFirstLine: string | null;
}

And the following function:

const onAddressSelected = (address: Address_findUserAddress) => {
    const mappedAddress = addressAnswerKeys.reduce(
      (acc, k) => ({ ...acc, [k.answerKey]: address[k.addressKey] AS_ONE_Of_Address_FindUserAddress }),
      {} as Record<string, string>
    );
    ...
  }

address[k.addressKey] - this piece of code says: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Address_findUserAddress'. No index signature with a parameter of type 'string' was found on type 'Address_findUserAddress'.

How to cast address[k.addressKey] AS_ONE_Of_Address_FindUserAddress as one of the keys of the address type? k.addressKey is string

CodePudding user response:

You can cast the key

address[k.addressKey as keyof Address_findUserAddress]
  • Related