首页 > 解决方案 > 如何使密钥可选?

问题描述

这是代码:

type TypeKey = 'A' | 'B' | 'C'
type Types = { [key in TypeKey] : string}

let myTypes : Types = {
    A : 'Apple',
    B : 'Banna'
}

这将有一个错误:

error: TS2741 [ERROR]: Property 'C' is missing in type '{ A: string; B: string; }' but required in type 'Types'.

如何使'C'可选?谢谢

标签: typescript

解决方案


可能有一种更优雅的方式,但您可以通过C从类型中删除然后将其作为可选属性添加回来来做到这一点:

type TypeKey = 'A' | 'B' | 'C'
// Remove C  vvvvv−−−−−−−−−−−−−−−−−−−−−−−−−−−−vvvvvv
type Types = Omit<{ [key in TypeKey] : string}, 'C'> & {C?: string}
// Add it back as an optional property −−−−−−−−−−−−−−^^^^^^^^^^^^^^

let myTypes : Types = {
    A : 'Apple',
    B : 'Banna'
}

游乐场链接


在您问过的评论中:

它有效,但有更好的方法吗?就像是type TypeKey = 'A' | 'B' | 'C?'

据我所知,没有,但你可以把它转过来,用以下方式定义TypeKeyTypes而不是相反:

interface Types {
    A: string;
    B: string;
    C?: string;
}

type TypeKey = keyof Types;

let myTypes : Types = {
    A : 'Apple',
    B : 'Banna'
}

游乐场链接


推荐阅读