如何允许作为 class 键的字符串
How to allow a string that is a key of a class
我有以下功能:
export const sortAlphabetically = <T>(array: T[], property: string) =>
array.sort((a: T, b: T) =>
a[property].localeCompare(b[property]));
property
应该是 T 中的一个键(作为字符串?),不应接受其他值。我尝试使用 property: [key in t]
但这不起作用。
有办法吗?
keyof
运算符应该可以做到这一点
export const sortAlphabetically = <
T extends Record<string, string>
>(array: T[], property: keyof T) =>
array.sort((a: T, b: T) => a[property].localeCompare(b[property]));
您需要向 TypeScript 保证 属性 的值是 string
。这就是为什么我使用 T extends Record<string, string>
我有以下功能:
export const sortAlphabetically = <T>(array: T[], property: string) =>
array.sort((a: T, b: T) =>
a[property].localeCompare(b[property]));
property
应该是 T 中的一个键(作为字符串?),不应接受其他值。我尝试使用 property: [key in t]
但这不起作用。
有办法吗?
keyof
运算符应该可以做到这一点
export const sortAlphabetically = <
T extends Record<string, string>
>(array: T[], property: keyof T) =>
array.sort((a: T, b: T) => a[property].localeCompare(b[property]));
您需要向 TypeScript 保证 属性 的值是 string
。这就是为什么我使用 T extends Record<string, string>