Typescript: How to Define interface with key in Enum

Typescript: How to Define interface with key in Enum

Can we define the interface with key in Enum ?

Can we define the interface with key in Enum

We cannot using enum as key in interface
But we can using enum as key in Type define.

Please see example bellow: 

enum AddressTypes {
WARD = 'ward',
DISTRICT = 'district',
PROVINCE = 'province',
COUNTRY = 'country',
}
// Solution 1:
type PersonAddress = Record<AddressTypes, string>;

// Solution 2:
type PersonAddress2 = { [key in AddressTypes]: string };

Conclusion

We can only using Enum as key in Type defination, we cannot using enum as key in interface defination. If you have any question, please comment bellow! Thanks !

Nhận xét

Bài đăng phổ biến từ blog này

TypeORM should using repository or query buider ?

Type of children prop in React Typescript

MSAL: Difference between Public Client Application And Confidential Client Application