我正在寻找一种用ts编写实现的方法,它能够拒绝一些带有查找类型的语句
有了这种执行:
function animalDecorator <O extends propertyof Animal>(property: O) {
// should allow only properties from
// a class that extends from Animal
}
class Animal { }
class Cat extends Animal {
static claws: any
}
class Stone {
static shape: any
}然后,键入以下代码,只有第一条语句才有效。
animalDecorator(Cat.claws) //allow
animalDecorator(Stone.shape) //deny发布于 2017-06-07 16:07:00
您可以使用typeof操作符来获取类的静态侧的类型。
换句话说,您可以将您的函数声明为
function animalDecorator(target: typeof Animal, property: any) { /*...*/ }如果您想以某种方式使用target类型,可以使用泛型:
function animalDecorators<T extends typeof Animal>(target: T, property: any): T { /*...*/ }最后,无法限制任意位置的值,但可以将函数限制为属性名称,如:
function animalDecorators<T extends typeof Animal>(target: T, property: keyof T) { /*...*/ }这样您就可以编写animalDecorator(Cat, "claws"),而不是animalDecorator(Cat, "shape")。
https://stackoverflow.com/questions/44416525
复制相似问题