Alex
Alex

Reputation: 67879

Is it possible to reference class property type?

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

Upvotes: 15

Views: 5965

Answers (1)

jcalz
jcalz

Reputation: 330216

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!

Upvotes: 26

Related Questions