Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Type of the current class as a type variable

I want to declare a function in TypeScript that returns the type of the current instance's type, e.g. in a fluent API that returns this.

Is there a type variable for "this type"? (I would rather not use the ugly Java way of X<T extends X<T>>.)

like image 391
billc.cn Avatar asked Jan 20 '15 14:01

billc.cn


People also ask

Can I use class as type in TypeScript?

TypeScript treats a class as both value and type. This implicit type declared by TypeScript describes the shape of the instance a class produces. Therefore when a class is used as a type, such as using let value :Class annotation, TypeScript checks if the value has all the public properties of the Class .

How do you check the data type of a variable in TypeScript?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.

How do you declare a variable in a TypeScript class?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.


1 Answers

There is not a way to do this yet in TypeScript. See issue https://github.com/Microsoft/TypeScript/issues/285 for voting/discussion.

like image 139
Ryan Cavanaugh Avatar answered Nov 07 '22 09:11

Ryan Cavanaugh