为什么打字稿会报错
interface IEmailUpdateCode {
userId: string;
smsCode: string;
newEmail: string;
}
const val1: IEmailUpdateCode = {
userId:"293842",
smsCode:"293480243",
newEmail:"abc@gm.com"
}
const data1:{
[key: string]: string | number;
} = val1;
//error: Type 'IEmailUpdateCode' is not assignable to type '{ [key: string]: string | number; }'
但是这样写没有错误
const val2:{
userId: string;
smsCode: string;
newEmail: string;
} = {
userId:"293842",
smsCode:"293480243",
newEmail:"abc@gm.com"
}
const data2:{
[key: string]: string | number;
} = val2;
如何使用 TS 接口使其工作?
here 是 TS 游乐场链接
答案 0 :(得分:0)
TypeScript 中的类型和接口之间存在细微差别。这个 GitHub 问题很好地解释了它:https://github.com/microsoft/TypeScript/issues/15300#issuecomment-332366024
TL;DR:此代码将起作用:
type IEmailUpdateCode = {
userId: string;
smsCode: string;
newEmail: string;
}
const val1: IEmailUpdateCode = {
userId:"293842",
smsCode:"293480243",
newEmail:"abc@gm.com"
}
const data1:{
[key: string]: string | number;
} = val1;