我已将数字值写入字符串变量,但没有出现错误,这是为什么?
https://codesandbox.io/s/lucid-elgamal-4lbin2
const BEApi = new Promise((resolve) => {
resolve({
string: 123
});
});
type MyDataType = {
string: string;
};
let myData: MyDataType | null = null;
const myResponce = async () => {
myData = (await BEApi) as MyDataType;
console.log(myData);
};
myResponce();
TypeScript 不够智能,无法从函数调用中推断出类型
resolve
。选项:
new Promise<MyDataType>...
),那么 TS 将能够检查调用是否resolve
对应于该类型;Promise.resolve
,然后 TS 可以推断返回类型(在您的简单示例中)。操场