0

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.

Nadiely Jade
  • 195
  • 2
  • 9
  • @PhilippMeissner I'm asking a comparison question – Nadiely Jade Mar 10 '21 at 07:14
  • Does this answer your question? [What are the difference between these type assertion or casting methods in TypeScript](https://stackoverflow.com/questions/49818305/what-are-the-difference-between-these-type-assertion-or-casting-methods-in-types) – Dane Brouwer Mar 10 '21 at 07:24
  • Hi @NadielyJade if you're satisfied with my answer please accept! Thanks – codeAligned Mar 26 '21 at 04:21

2 Answers2

1

The as keyword is used as type assertion in typescript

Muiz Uvais
  • 68
  • 2
  • 12
1

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".

codeAligned
  • 179
  • 2
  • 3
  • 9