Typescript泛型中对接口成员的约束 [英] Constraints on interface members in typescript generics
问题描述
我有一个方法,只要它的所有字段都是字符串或数字,它就可以接受任何对象
I have a method, that should accepts any object, as long as all its fields are strings or numbers
我做到了这一点,它与鸭子输入非常有用
I made this, which works great with duck typing
static interpolateParams(
route: string,
params: {[key: string] : string | number}) : string {
const parts = route
.split("/")
.map(part => {
const match = part.match(/:([a-zA-Z09]*)\??/);
if (match) {
if (!params[match[1]]) {
console.error("route argument was not provided", route, match[1]);
return part;
}
return params[match[1]];
}
else {
return part;
}
})
return "/" + parts.slice(1).join("/");
}
并致电
interpolateParams("/api/:method/:value", {method: "abc", value: 10});
现在我想让 interpolateParams
接受路由 params
的任何接口。
Now I want to make interpolateParams
to accept any interface for route params
.
interpolateParams<IABCParams>("/api/:method/:value", {method: "abc", value: 10});
问题是,对于所有字符串或数字字段,它仍然应该匹配约束
是否可以在给定接口的所有字段上将通用约束指定为特定类型?
Is there a way to specify generic constraint on all fields of given interface to be of certain type?
我尝试过
static interpolateParams<T extends {[key: string] : string | number}>(
route: string,
params: T) : string {
显然得到了这个
类型'IABCParams'不满足约束'{{key:string]:string |数; }'。
Type 'IABCParams' does not satisfy the constraint '{ [key: string]: string | number; }'.
'IABCParams'类型缺少索引签名。
Index signature is missing in type 'IABCParams'.
谢谢
推荐答案
T
的约束可以引用 T
(有一些限制),因此您可以使用映射类型来生成约束,该约束具有与 T
相同的字段:
T
's constraint can refer to T
(with some restrictions), so you can use a mapped type to generate a constraint that has the same fields as T
:
function interpolateParams<T extends {[P in keyof T] : string | number}>(
route: string,
params: T) : string { /*...*/ }
请注意,使用圆形类型参数约束的欺骗有时可能会导致问题,尽管这种情况很可能会解决。
Beware that trickery with circular type parameter constraints can sometimes cause problems, though this scenario will likely be OK.
这篇关于Typescript泛型中对接口成员的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!