signature=1be7575a614ba3597c2c53247a739d1c,An index signature parameter type cannot be a union type....

最近在写接口类型时,希望一个类型的键值是联合类型中固定的几个

例如

const enum INFO_KEYS{

TEL = 'tel',

AGE = 'age',

}

// or

// type IInfoKeys = 'tel' | 'age';

export interface IPersonnalInfo = {

area_id: number;

area_name: string;

[key: INFO_KEYS]: number; // or [key: IInfoKeys]: number;

}

但是却得到错误提示

An index signature parameter type cannot be a union type. Consider using a mapped object type instead. ts(1337)

下面是我对解决方法的总结

解决方案

解决该问题,我们只需要注意以下三个地方

使用[key in INFO_KEYS],而不是[key: INFO_KEYS]

这也是很多回答给出的方案,但事实上?

export interface IPersonnalInfo = {

area_id: number;

area_name: string;

[key in INFO_KEYS]: number

}

在使用in之后,仍然会得到错误提示

A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type. ts(1169)

A computed property name must be of type 'string', 'number', 'symbol', or 'any'. ts(2464)

因为接下来还有两点需要注意

如果类型是interface,使用type类型别名替换

export type IPersonnalInfo = {

area_id: number;

area_name: string;

[key in INFO_KEYS]: number;

};

分离类型中的其他成员,使用相交类型来组织它们

type IAreaInfo = { //type or interface

area_id: number;

area_name: string;

}

export type IPersonnalInfo = {

[key in INFO_KEYS]: number;

} & IAreaInfo;

最后

如果注意了以上三点 ,我们最终得到的代码会是这样,并且没有错误提示

const enum INFO_KEYS{

TEL = 'tel',

AGE = 'age'

}

// or

// type IInfoKeys = 'tel' | 'age';

type IAreaInfo = {

area_id: number;

area_name: string;

}

export type IPersonnalInfo = {

[key in INFO_KEYS]: number; //or [key in IInfoKeys]: number;

} & IAreaInfo;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值