Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
Alex Avatar asked Oct 12 '17 08:10

Alex


1 Answers

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!

like image 77
jcalz Avatar answered Oct 11 '22 19:10

jcalz