typescript 如何类型检查如果一个对象属性有一个值,那么其他属性也应该有相应的值

szqfcxe2  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(145)

如何在一个对象中类型检查,如果一个属性有一个特定的值,另一个属性应该有相应的值在typescript中?

toiithl6

toiithl61#

选项1:创建联合类型

export type Status1 = typeof StatusTypes[number] & {
    desc: string;
    count: number | null
}

选项2:生成泛型类型

export interface Status2<Id extends typeof StatusTypes[number]['id']> {
    id: Id,
    name: Extract<typeof StatusTypes[number], { id: Id }>['name'],
    desc: string;
    count: number | null
}

旁注:
将类型保存为Map而不是数组可能更简洁

type StatusTypes = {
    1: { id: 1, name: 'Failed', },
    2: { id: 2, name: 'Awaiting', },
    3: { id: 3, name: 'Running', },
    4: { id: 4, name: 'Processed', },
}

根据您的环境和类型源考虑这一点

相关问题