Typescript 可以在TS中创建类型安全的函数集合吗?
我正在写一个小的库来简化使用redux的工作,但是我一直在打字。 我想做的基本上可以归结为以下几点:Typescript 可以在TS中创建类型安全的函数集合吗?,typescript,interface,Typescript,Interface,我正在写一个小的库来简化使用redux的工作,但是我一直在打字。 我想做的基本上可以归结为以下几点: 父类将动作描述符处理为动作 子类提供所述描述符 问题是,在子对象中定义的类型信息在该过程中丢失 最小测试用例如下所示: type callable = (...args: any[]) => any interface CallableCollection { [s: string]: callable } class Parent { functions: Call
- 父类将动作描述符处理为动作
- 子类提供所述描述符
type callable = (...args: any[]) => any
interface CallableCollection {
[s: string]: callable
}
class Parent {
functions: CallableCollection
constructor() {
this.functions = this.a;
}
get a(): CallableCollection {
return {};
}
}
class Child extends Parent {
get a() {
return {
a: (x: string) => x,
b: (x: number) => x,
}
}
}
const test = new Child();
test.a.a(5);//type error
test.functions.a(5);// no type errors
我可以通过使类泛型并提供所有需要的类型作为类型参数来使它正常工作,但从类用户的角度来看,它看起来非常蹩脚
有没有一种方法可以让它在TS中很好地工作,而不用在泛型类中提供类型作为参数?我想这取决于您的实际用例,但是当所讨论的特定类型可以从子类的其他属性派生时,您有时可以使用它来代替泛型:
interface CallableCollection {
[s: string]: (...args: any[]) => any;
}
class Parent {
functions: this["a"]; // polymorphic this and a lookup of "a"
constructor() {
this.functions = this.a;
}
get a(): CallableCollection {
return {};
}
}
class Child extends Parent {
get a() {
return {
a: (x: string) => x,
b: (x: number) => x
};
}
}
const test = new Child();
test.a.a(5); //type error
test.functions.a(5); // type error
这对你有用吗?希望有帮助;祝你好运 我想这取决于您的实际用例,但当所讨论的特定类型可从子类的其他属性派生时,您有时可以使用来代替泛型:
interface CallableCollection {
[s: string]: (...args: any[]) => any;
}
class Parent {
functions: this["a"]; // polymorphic this and a lookup of "a"
constructor() {
this.functions = this.a;
}
get a(): CallableCollection {
return {};
}
}
class Child extends Parent {
get a() {
return {
a: (x: string) => x,
b: (x: number) => x
};
}
}
const test = new Child();
test.a.a(5); //type error
test.functions.a(5); // type error
这对你有用吗?希望有帮助;祝你好运 那很有帮助,谢谢。但是我能做一些更高级的东西吗,比如函数:{callbacks:this[“a”]}?是的,但是编译器只喜欢在某些地方把
this
看作一个类型。。您可能可以创建一个类型别名来帮助。。。e、 例如,type Callbacks={Callbacks:T}
然后是以后的类父{functions:Callbacks;
这非常有用,谢谢。但是我可以做一些更高级的东西吗,比如函数:{Callbacks:this[“a”]}?是的,但是编译器只喜欢在某些地方把this
看作一个类型。你可能会制作一个类型别名来帮助…例如,type Callbacks={callbacks:T};
以及以后的类父级{函数:回调;