typescript - 打字稿属性选择器
问题描述
我需要基于对象属性的简单类型检查,我想像这样使用它:
type User = { id: string, name: string }
sort<User>("name");
Intellisense 为我提供“名称”或“ID”以供输入,或者在输入其他内容时显示“错误”。
尽管我只能传递值,但我当前的实现property
不是 type 。string
string
sort<T extends { [key: string]: any }>(property: keyof T) {
// how can I make 'property' string ???
// required API object is e.g. { property: "Id", desc: true }
}
这里是游乐场。
解决方案
即使你的约束实际上有一个字符串索引器,keyof T
它仍然可能是一个number
所以keyof T
最终会是string | number
您可以使用Extract
箭头指向字符串:
type Custom = {
property: string, //ok
desc: boolean
}
function sort<T>(property: Extract<keyof T, string>): Custom {
return {
property: property,
desc: false
}
}
type User = { id: string, name: string }
sort<User>("name");
推荐阅读
- python - 使用 python 3.7.7 连接到引擎时出现 SqlAlchemy 错误
- firebase - 未定义的类“FirebaseUser”
- email - 设置使用 Google App Script 创建的新幻灯片的权限
- javascript - How to convert normal PDF to AcroForm?
- swift - Want to resize a image with better resolution in swift
- javascript - 打字稿类型“未知”不可分配给类型“数字”
- azure - 为什么 Azure QueueTriggered 函数应用会引发超时异常?
- android - 更新应用程序版本后通知声音不起作用
- rust - 导入其他依赖项需要的依赖项版本
- c# - 在 C# 中解构元组的性能损失?