首页 > 解决方案 > 打字稿属性选择器

问题描述

我需要基于对象属性的简单类型检查,我想像这样使用它:

type User = { id: string, name: string }
sort<User>("name");

Intellisense 为我提供“名称”或“ID”以供输入,或者在输入其他内容时显示“错误”。

尽管我只能传递值,但我当前的实现property不是 type 。stringstring

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 }
}

这里是游乐场

标签: typescripttypescript-typings

解决方案


即使你的约束实际上有一个字符串索引器,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");


推荐阅读