what kind of Anonymous Classes syntax is this in typescript?

Viewed 43
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?

2 Answers

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

But if you wanted to see Myinterface (the name) as the type of mylet when you hover it with the mouse, you could type it explicitly (I typically do, so that if I come back later and change the contents of the object, any changes that aren't compatible with Myinterface get flagged up):

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

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