Home > front end >  what kind of Anonymous Classes syntax is this in typescript?
what kind of Anonymous Classes syntax is this in typescript?

Time:11-17

interface Myinterface extends interface1 {
    name: string;
}

let mylet = <Myinterface >{};

mylet.name = "nana";
 

what is < Myinterface>{} ?? Is this one of the ways to create an object without a class?

CodePudding user response:

It's a type assertion, another way of writing:

let mylet = {} as Myinterface;

It says "The object ({}) I'm assigning to mylet is of type Myinterface" (even though, in that code, it isn't — yet, not until you add the name property).

The <Myinterface>{} version is less common these days because of JSX, which wants to use <Myinterface> to start an element.

Given the question, I'm guessing you didn't write that code. For what it's worth, that code would be better written as:

let mylet = {
    name: "nana",
};

That has the same result as:

let mylet = {} as Myinterface;
mylet.name = "nana";

...since TypeScript's type system is structural (based on shapes), not nominal (based on names).

CodePudding user response:

That is a type assertion. What you have there is the creation of an empty object {} and then asserting that the empty object respects the interface Myinterface.

Typescript will only perform minimal checks on assertions, so you can assert that {} respects the Myinterface even though it does not in this case (name is required). This is usually only a good idea if you then add the missing properties

Another form of type assertion would be {} as MyInterface

  • Related