typescript - 如何允许作为类键的字符串
问题描述
我有以下功能:
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]
但这不起作用。有没有办法做到这一点?
解决方案
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>
推荐阅读
- python - 如何将额外的参数传递给 django 日志格式化程序
- python - 将我自己的数据添加到 Python 中的 Plotly 图表中?
- jenkins - 当从 github Jenkins 管道中删除分支时,有没有办法自动删除分支而不是交叉线
- mpi - 重叠的通信和计算问题
- symfony - 在 Symfony 中有条件地隐藏一些嵌入的表单字段(集合)
- javascript - 将根 JSON 对象值设置为数组
- raspberry-pi - 在 Arduino 上设置 ATSAM3X8E 以进行 SPI 从机操作
- c - MPI_File_write C
- javascript - javascript函数返回为“null”而不是null值
- android - Ionic Cordova Themeable Browser - 防止 youtube 视频在后台播放