【发布时间】:2022-09-30 13:01:01
【问题描述】:
我有一个函数应该返回另一个函数来通过指定的键比较两个对象,如下所示:
function compareTexts(text1: string, text2: string, caseSensitive = false): 0 | -1 | 1 {
const t1 = (caseSensitive ? text1 : text1.toLowerCase()).trim();
const t2 = (caseSensitive ? text2 : text2.toLowerCase()).trim();
return t1 === t2 ? 0 : t1 < t2 ? -1 : 1;
}
function compareByProp(prop: string) {
return (a: any, b: any) => compareTexts(a[prop], b[prop]);
}
(参见 typescript playground 示例)
我想摆脱any 类型,并返回一个只接受带有prop 键的对象的函数。
像这样:
// this should be OK
console.log( compareByProp(\'name\')({ name: \'sas\', age: \'2\' }, { name: \'aaa\', age: \'5\' }))
// this should err, because objects don\'t have the `agex` property
console.log( compareByProp(\'agex\')({ name: \'sas\', age: \'2\' }, { name: \'aaa\', age: \'5\' }))
我试过这个:
function compareByProp(prop: string) {
return (a: { [prop]: string }, b: { [prop]: string }) => compareTexts(a[prop], b[prop]);
}
但我收到以下错误:A computed property name in a type literal must refer to an expression whose type is a literal type or a \'unique symbol\' type.(1170)
知道如何实现它,或者更好的方法来处理它吗?
-
this 对你有用吗?我们只是使用泛型来“存储”传递的内容,然后使用它为
a和b创建类型。 -
太好了,请将其发布为答案,以便我接受
标签: typescript