简体   繁体   English

如何允许作为类键的字符串

[英]How to allow a string that is a key of a class

I have the following function:我有以下功能:

export const sortAlphabetically = <T>(array: T[], property: string) => 
    array.sort((a: T, b: T) => 
    a[property].localeCompare(b[property]));

The property should be a key in T (as string?), no other values should be accepted.property应该是 T 中的一个键(作为字符串?),不应接受其他值。 I tried with property: [key in t] but this doesn't work.我尝试使用property: [key in t]但这不起作用。 Is there a way to do this?有没有办法做到这一点?

keyof operator should do the trick keyof运算符应该可以解决问题

Docs 文档

export const sortAlphabetically = <
  T extends Record<string, string>
>(array: T[], property: keyof T) =>
  array.sort((a: T, b: T) => a[property].localeCompare(b[property]));

You need to assure TypeScript that value of property is string .您需要确保 TypeScript 的属性值为string That's why I have used T extends Record<string, string>这就是为什么我使用T extends Record<string, string>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM