Javascript 在构造函数调用中使用泛型类型而不在参数中使用类型
是否可以在构造函数调用中使用泛型而不使用类似参数中的类型,或者是否有其他方法可以做到这一点Javascript 在构造函数调用中使用泛型类型而不在参数中使用类型,javascript,generics,flowtype,Javascript,Generics,Flowtype,是否可以在构造函数调用中使用泛型而不使用类似参数中的类型,或者是否有其他方法可以做到这一点 type PersonProps = { name: string, } class Model<P> { label: string; constructor(label: string) { this.label = label; } create(props: P): Promise<any> { ... } } const Person
type PersonProps = {
name: string,
}
class Model<P> {
label: string;
constructor(label: string) {
this.label = label;
}
create(props: P): Promise<any> { ... }
}
const Person = new Model<PersonProps>('Person');
type PersonProps={
名称:string,
}
班级模式{
标签:字符串;
构造函数(标签:字符串){
this.label=标签;
}
创建(props:P):承诺{…}
}
const Person=新型号(“Person”);
编辑:
我在Visual Studio代码中遇到以下流错误,并且根本没有自动完成结果:
test.js:11
11: const Person = new Model<PersonProps>('Person');
^^^^^^^^^^^^^^^^^^^^^ boolean. This type cannot be compared to
11: const Person = new Model<PersonProps>('Person');
^^^^^^^^ string
test.js:11
11: const Person = new Model<PersonProps>('Person');
^^^^^^^^^^^ PersonProps. type referenced from value position
5: type PersonProps = {
^^^^^^^^^^^ type PersonProps
test.js:11
11:const Person=新型号(“Person”);
^^^^^^^^^^^^^^^^^^^^^布尔型。此类型无法与
11:const Person=新型号(“Person”);
^^^^^^^^串
test.js:11
11:const Person=新型号(“Person”);
^^^^^^^^^^^个人道具。从值位置引用的类型
5:类型PersonProps={
^^^^^^^^^^^打字道具
您不需要(事实上不能)在此处指定类型参数:
const Person = new Model('Person');
如果要使用type参数为Person
变量指定完整类型,可以添加类型注释:
const Person: Model<PersonProps> = new Model('Person');
const Person:Model=newmodel('Person');
您看到的错误是由于
字符在该上下文中解析为“小于”和“大于”。来自:“这是一个元标记,不应使用。有关详细信息,请参阅wiki。”你的意思是?@T.J.Crowder谢谢我添加了错误。但是如果我调用create方法,我不会得到自动完成的结果。啊,在这种情况下,你可以注释Person:const Person:Model=new Model('Person')
。这对你有用吗?抱歉,但我不太明白你所说的注释这个人是什么意思?编辑:谢谢,给我一点时间,我会试试;)我按了回车键才想这么做。我用一行代码编辑了评论。谢谢,它有效:)你能编辑你的答案吗,这样我就可以接受它作为答案了?