admin管理员组文章数量:1794759
Typescript ques:An index signature parameter type cannot be a union type. Consider using a mapped...
写接口类型时,希望一个类型的键值是联合类型中固定的几个
const enum MSGTYPE{ TEXT = 'text', IMAGE = 'image', } // or // type MSGTYPE = 'text' | 'image'; export interface QywxSendMessage = { msg_id: number; msg_name: string; [key: MSGTYPE]: number; }显然会报错An index signature parameter type cannot be a union type. Consider using a mapped object type instead. ts(1337)
问题及解决方式呢: github/microsoft/Typescript/issues/33440 github/Microsoft/TypeScript/issues/24220 github/Microsoft/TypeScript/issues/2491
export interface QywxSendMessage = { msg_id: number; msg_name: string; [key in MSGTYPE]: number; }写接口类型时,希望一个类型的键值是联合类型中固定的几个中的一个
type MSGTYPE = 'text' | 'image'; export interface QywxSendMessage = { msg_id: number; msg_name: string; [key: MSGTYPE]: number; // [key: 'text' | 'image']: number; }显然也会报错An index signature parameter type cannot be a union type. Consider using a mapped object type instead. ts(1337)
那该如何表示呢?如果用?那显然是有问题的
type MSGTYPE<T> = {'text': T } | {'image':T }; export interface QywxSendMessageParams = { msg_id: number; msg_name: string; } export type QywxSendMessage = QywxSendMessageParams & MSGTYPE<number>;本文标签: INDEXsignatureTypescriptquesunion
版权声明:本文标题:Typescript ques:An index signature parameter type cannot be a union type. Consider using a mapped... 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686549875a80734.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论