Explain how as works please:
I have a simple interface.
interface myModel {
name: string;
id: number;
}
and there is a function that returns an object { } as myModel;
function getMyModel(): myModel{
return {
name: 'kek',
id: 8,
data: 'pew',
names: '321'
} as myModel
}
Why, if I add properties that are not in myModel , the compiler does not throw an error and logs an object with properties that are not in the myModel interface?
console.log(getMyModel());
//[LOG]: {
// "name": "kek",
// "id": 8,
// "data": "pew",
// "names": "321"
//}
How does as work?
And why if I write like this:
let test: myModel = {
name: 'kek',
id: 8
data: 'pew',
names: '321'
}
then on the line with data: 'pew', the compiler will highlight it as an error?
ascompletely overrides type checking.When you use it, you are telling the compiler that the object is of type
myModeland it will treat it as such.It is a way to tell the compiler that you, the programmer, know what type the object it better than the compiler does.
In your particular example the
asstatement is very clearly a lie.It makes more sense when you have something like:
...since TypeScript only knows that the
json()method returns something that can be parsed from JSON (so a string, or a number, or any kind of basic object, etc, etc).I generally prefer to avoid
asentirely in favour of performing a runtime check with a custom type guard function so if something goes wrong (e.g. the API design changing and returning JSON in a different shape) then I can catch it early and with a clearer error message).