Is it possible to reference class property type?

Alex

I have a class:

class Todo {
    public id: number;
}

Is it possible to use class property as type reference (get number type), like:

interface Settings {
    selectedTodoId: Todo.id;
}

property selectedTodoId should be now checked for number type

jcalz

Yes, this is possible, using lookup types. The trick is to use bracket notation (Todo['id']) instead of dotted notation (Todo.id) Dotted notation would be very convenient, and there is a suggestion to allow this, but it isn't trivial to implement and would break existing code (it conflicts with namespacing), so for now the bracket notation is the way to go.

Here's how you do it:

class Todo {
    public id: number;
}

interface Settings {
    selectedTodoId: Todo['id'];
}

You can verify that selectedTodoId has type number as desired.

Hope that helps; good lcuk!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Is it possible to reference an implementing type in an abstract class method type in TypeScript?

Struct contains property with reference type/class causing memory leak

How it is possible to call methods of Object class on a reference of Interface type?

How to reference the type of a property?

Reference class property in for loop

Reference to class object property

"Property reference" of the class

Possible to reference extended property in less?

TypeScript: Is it possible to implement abstract class property by property inherited from type specified in abstract one?

Class instance reference from property

Pass Class Property by Reference in PowerShell

Typescript: Is it possible to reference type aliases

Is it possible for the template parameter to be a reference type?

CollectionViewSource as Class Property Type

generic type of class property

Property as a Function Type in a Class

In Java is it possible to assign a method reference to a variable whose class has a generic type?

Is it possible to reference a property in package.json

What is the type of a reference of a reference in a template class

Is it possible to exclude certain property (Like class type) from being copied during struct copy?

Is it possible to create generic class which only accepts a type which has a certain property

Type reference to constructor of a class in Typescript?

typescript: reference current class type

What is the type hint for a class reference?

Reference class type in dataclass definition

Class Template and Reference Return Type

Find the Class Reference Of Genric Type

how to reference the Type in the Concrete class of a generic class

Typescript class property type based on a property value