Home > OS >  Is there any better way of writing interfaces if all the items are string in object?
Is there any better way of writing interfaces if all the items are string in object?

Time:12-10

I have a interface like this:

interface companyInfoProps {
  account: {
    merchantName: string;
    loginMailAddress: string;
    loginPhone: string;
    vknTcknNumber: string;
    invoiceAddress: string;
  };
  district: string;
  city: string;
}

As you can see every items in the object are string type. Is there any better way to write this interface? Or I just have to write :string next to every element?

CodePudding user response:

You can use Record<Keys, Type> utility type:

Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.

Second argument of Record will be applied to each key.

type AccountKeys =
    | 'merchantName'
    | 'loginMailAddress'
    | 'loginPhone'
    | 'vknTcknNumber'
    | 'invoiceAddress'

interface CompanyInfoProps {
    account: Record<AccountKeys, string>;
    district: string;
    city: string;
}

Please keep in mind, that your example is perfectly valid. I can't say that my approach is better in some way. It just a different approach.

I think it worth reading about: utility types and mapped types

  • Related