英文:
Enforce type of property to sort by in typescript
问题
我想按TypeScript中的数值属性对对象数组进行排序。
为了实现这一目标,我有以下代码。这个代码的问题在于它不强制要求T
类型的prop
键下的值必须是数字。当然,我可以在运行时检查arr
中的任何值的类型,但我想知道如何通过TypeScript在编译时强制执行这一要求。
function sortByProperty<T>(arr: T[], prop: keyof T): T[] {
return arr.sort((a, b) => a[prop] - b[prop]);
}
英文:
I want to sort an array of objects by a numeric property in typerscript.
To do this, I've got the below code. This has the problem that it doesn't enforce that the value at the prop
key of T
need be numeric. Of course I could just check this at runtime with checking the type of any of the values in arr
, but I would like to know how to enforce this at compile time through the use of typescript.
function sortByProperty<T>(arr : T[], prop : keyof T) : T[] {
return arr.sort((a, b) => a[prop] - b[prop]);
}
答案1
得分: 1
以下是代码部分的中文翻译:
function sortByProperty<T extends Record<K, number>, K extends PropertyKey>(
arr: T[],
prop: K & keyof T
): T[] {
return arr.sort((a, b) => a[prop] - b[prop]);
}
我们将prop
的类型存储在一个新的泛型类型K
中,并强制要求T
必须是一个对象类型,其中属性K
的类型是number
。
这会导致在选择不对应number
属性的属性名称时产生编译时错误。
// 有效
sortByProperty([{
a: "",
b: "",
c: 0
}], "c")
// 错误:类型'string'不能赋值给类型'number'
sortByProperty([{
a: "",
b: "",
c: 0
}], "a")
英文:
A simple solution would look like this:
function sortByProperty<T extends Record<K, number>, K extends PropertyKey>(
arr: T[],
prop: K & keyof T
): T[] {
return arr.sort((a, b) => a[prop] - b[prop]);
}
We store the type of prop
in a new generic type K
and enforce that T
must be an object type where the type of the property K
is number
.
This leads to a compile time error, if we choose a property name which does not correspond to a number
property.
// valid
sortByProperty([{
a: "",
b: "",
c: 0
}], "c")
// Error: Type 'string' is not assignable to type 'number'
sortByProperty([{
a: "",
b: "",
c: 0
}], "a")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论