以enum字段和随机字符串作为键键入



我有一个像这样的enum

export enum Test {
A = 'A',
B = 'B',
C = 'C'
}

我想要一个类型,可以为这个enum的每个字段a, B, C都有字段,但也可以将相同的字段与字符串连接起来,如'A_2', 'B_2', 'C_2'

对于A B C部分,我选择了这个类型

type TestExtended =  { [p in keyof typeof Test]: string } 

我如何完成它来得到'A_2', 'B_2', 'C_2' ?

也许你可以使用这样的东西(Partial是可选的):

type TestExtended = Partial<Record<`${keyof typeof Test}_2`, string>>;
const testExtended: TestExtended = { A_2: 'foo' };

或者甚至像这样:

type TestExtended<T extends string = ''> = Partial<Record<`${keyof typeof Test}${T}`, string>>;
const testExtended: TestExtended<'_2'> = { A_2: 'bar' };

您可以重新映射键以与_2连接:

type TestExtended =  { [P in keyof typeof Test as `${P}_2`]: string };

最新更新