class Route<T> {
path: string;
constructor(path: string) {
this.path = path;
}
getLink(params: T) {
if (!params) {
return this.path;
}
return `${this.path}/${params.join('/')}`;
}
}
const routeA = new Route<{ id: number }>('/something/amazing');
// should not be possible
routeA.getLink();
// only this should be valid
routeA.getLink({ id: 1 });
嗨-我想拥有一个采用通用参数T(参数)的Route类。每个路线可能都有一些参数,也可能根本没有。
然后应该可以调用routeA.getLink()
并正确键入其参数。
const a = new Route('index'); // takes no parameters
a.getLink() // only this is valid
a.getLink({ something: 1}) // invalid
const b = new Route<{ id: number }>('post'); // takes no parameters
b.getLink() // invalid
b.getLink({ id: 1}) // valid
如何输入?
一些帮助将不胜感激:)谢谢!
您可以使用函数重载和默认的null
forT
来确保某些重载仅对某些特定的有效this
:
class Route<T = null> {
path: string;
constructor(path: string) {
this.path = path;
}
getLink(this: Route<null>): string;
getLink(this: Route<T>, params: T): string;
getLink(params?: T) {
if (!params) {
return this.path;
}
return `${this.path}/${params.join('/')}`;
}
}
const a = new Route('index'); // takes no parameters
a.getLink() // only this is valid
a.getLink({ something: 1 }) // invalid
const b = new Route<{ id: number }>('post'); // takes no parameters
b.getLink() // invalid
b.getLink({ id: 1 }) // valid
另一种解决方案是声明两个构造函数签名,分别是通用签名和非通用签名,每个签名都返回不同的类型签名:
class RouteImpl<T> {
path: string;
constructor(path: string) {
this.path = path;
}
getLink(params?: T) {
if (!params) {
return this.path;
}
return `${this.path}/${params.join('/')}`;
}
}
const Route: {
new (path: string) : {
path: string,
getLink(): string;
}
new <T>(path: string) : {
path: string,
getLink(params:T): string;
}
} = RouteImpl;
const a = new Route('index'); // takes no parameters
a.getLink() // only this is valid
a.getLink({ something: 1 }) // invalid
const b = new Route<{ id: number }>('post'); // takes no parameters
b.getLink() // invalid
b.getLink({ id: 1 }) // valid
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句