[英]Typescript generic class in object
I want to do a generic typescript class.我想做一个通用的 typescript class。 But it doesn't work when the class is inside an object.但当 class 位于 object 内时,它不起作用。 I've tried a lot of codes, but they don't work for me:(我已经尝试了很多代码,但它们对我不起作用:(
I have tried all of this.我已经尝试了所有这些。
// this is my class object
const obj1 = {
Foo: class<T> {
foo: T
constructor({ foo }: { foo: T }) {
this.foo = foo;
}
getFoo(): T {
return this.foo
}
setFoo(t: T): T {
this.foo = t
return this.foo
}
}
}
// This works: it is typechecked
let a = new obj1.Foo({ foo: 0 })
a.getFoo() // number
a.setFoo('123') // error
// None of this works
// uncomment them to see errors
// let b: obj1.Foo = new obj1.Foo({ foo: 0 })
// let b: obj1.Foo<number> = new obj1.Foo({ foo: 0 })
// let b: typeof obj1.Foo = new obj1.Foo({ foo: 0 })
// let b: typeof obj1.Foo<number> = new obj1.Foo({ foo: 0 })
// let b: typeof obj1.Foo.prototype = new obj1.Foo({ foo: 0 })
// let b: typeof obj1.Foo.prototype<number> = new obj1.Foo({ foo: 0 })
// let b: typeof obj1["Foo"]["prototype"] = new obj1.Foo({ foo: 0 })
// let b: typeof obj1["Foo"]["prototype"]<number> = new obj1.Foo({ foo: 0 })
b.getFoo() // any
b.setFoo('123') // works (it should error instead)
typescript playground link typescript 操场链接
thanks but sorry for bad english谢谢,但抱歉英语不好
That's how you can do what you want:这就是你可以做你想做的事:
namespace customNamespace {
export class Foo<T> {
private foo: T;
constructor({ foo }: { foo: T }) {
this.foo = foo;
}
getFoo(): T {
return this.foo;
}
setFoo(t: T): T {
this.foo = t;
return this.foo;
}
}
}
// This works: it is typechecked
let a = new customNamespace.Foo({ foo: 0 });
a.getFoo(); // number
a.setFoo('123'); // error
// None of the following are typechecked
// uncomment them to see errors
// let b: obj1.Foo = new obj1.Foo({ foo: 0 })
let b: customNamespace.Foo<number> = new customNamespace.Foo({ foo: 0 });
// let b: typeof obj1.Foo = new obj1.Foo({ foo: 0 })
// let b: typeof obj1.Foo<number> = new obj1.Foo({ foo: 0 })
// let b: typeof obj1.Foo.prototype = new obj1.Foo({ foo: 0 })
// let b: typeof obj1.Foo.prototype<number> = new obj1.Foo({ foo: 0 })
// let b: typeof obj1["Foo"]["prototype"] = new obj1.Foo({ foo: 0 })
// let b: typeof obj1["Foo"]["prototype"]<number> = new obj1.Foo({ foo: 0 })
b.getFoo() // old: any, now: typechecked!
b.setFoo('123') // old: works (it should error instead), now: got an error!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.