Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does typesript not respond to type when promis?

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading