I get a correct result although there should be an error. why does typesript not respond to type when promis?
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();
>Solution :
A type assertion tells TypeScript that a value is the specified type.
It explicitly overrides all type checks.
You said (await BEApi) as MyDataType and TypeScript trusts you.
I recommend avoiding as. A better way to describe the types would be to specify that new Promise should resolve as MyDataType.
This will cause TypeScript to report an error when you try to resolve it with a value that does not conform to that type.
type MyDataType = {
string: string;
};
const BEApi = new Promise<MyDataType>((resolve) => {
resolve({
string: 123
});
});
let myData: MyDataType | null = null;
const myResponce = async () => {
myData = await BEApi;
console.log(myData);
};
myResponce();