首页 > 解决方案 > 如何允许作为类键的字符串

问题描述

我有以下功能:

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

应该是 T 中的property键(作为字符串?),不应接受其他值。我试过了,property: [key in t]但这不起作用。有没有办法做到这一点?

标签: typescriptimplicit-typing

解决方案


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 保证 property 的值为string. 这就是我使用的原因T extends Record<string, string>


推荐阅读