Does this normal declaration
let myArrayObject: Array<{id: String, name: String}> = [];
different than using as
like
const myArrayObject = [] as Array<{id: String, name: String}>
I find as is more readable though.
Does this normal declaration
let myArrayObject: Array<{id: String, name: String}> = [];
different than using as
like
const myArrayObject = [] as Array<{id: String, name: String}>
I find as is more readable though.
The normal declaration is assigning a type to the object. "as" is casting the object to have a specific type, no matter the type inferred by TypeScript automatically.
For example, let's look at the following code.
interface User {
name: string;
age: number;
occupation: string;
}
const myself = {name:"andy"} as User
The object myself does not have all the fields required by the "User" interface. But we can tell typescript to treat "myself" as a "User". This is useful in many cases, for example if there's some function that is expecting "User" objects as input but we want it to accept an object that does not have all the properties defined in "User".