是否可以引用 class 属性 类型?

Is it possible to reference class property type?

我有一个class:

class Todo {
    public id: number;
}

是否可以使用 class 属性 作为类型参考(获取数字类型),如:

interface Settings {
    selectedTodoId: Todo.id;
}

属性 selectedTodoId 现在应该检查 number 类型

是的,这是可能的,使用 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 允许这样做,但实现起来并不容易,并且会破坏现有代码(它与命名空间冲突),所以现在括号表示法是这样去。

操作方法如下:

class Todo {
    public id: number;
}

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

您可以根据需要验证 selectedTodoId 的类型 number

希望对您有所帮助;好样的!