打字稿中的联合类型?

时间:2018-06-27 12:21:24

标签: typescript typescript2.0

为什么TypeScript中不允许这种类型的定义?

type profileType = 'TEACHER' | 'PRINCIPAL';

interface FormList {
    [ key: profileType ] : IForm[];
}

let forms: FormList;

forms = {
    'TEACHER' : [{ id: 1, name: "o" }, { id: 1, name: "b" }]
}

它将在以下行中引发错误:[ key: profileType ] : IForm[];

1 个答案:

答案 0 :(得分:1)

您可以将字符串文字从并集映射为新类型。这在打字稿中称为mapped type

type IForm = {};
type ProfileType = 'TEACHER' | 'PRINCIPAL';    

type FormList = { [P in ProfileType]: IForm[] };

let forms: FormList;

forms = {
    'TEACHER': [{ id: 1, name: "o" }, { id: 1, name: "b" }],
    'PRINCIPAL': [{ id: 1, name: "o" }, { id: 1, name: "b" }]
}