← 中文资源

简体中文版本

PickByValue 按值类型筛选字段

映射类型的 as 子句按值类型过滤字段:PickByValue 只保留匹配 string、Date、string[] 的字段,keyof 再取出字段名联合,序列化与表单场景正好需要这种按类型成组。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

u1 Ada
2026-01-01
core,edge createdAt

实现说明

模块级对象字面量,键名固定:id、name。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。

核心语句

type PickByValue<T, V> = { [K in keyof T as T[K] extends V ? K : never]: T[K] };
type DateKeys = keyof PickByValue<User, Date>;

代码示例

interface User {
  id: string;
  name: string;
  age: number;
  createdAt: Date;
  tags: string[];
}

// PickByValue keeps only the fields whose value type extends V
type PickByValue<T, V> = { [K in keyof T as T[K] extends V ? K : never]: T[K] };

type StringFields = PickByValue<User, string>; // id, name
type DateFields = PickByValue<User, Date>; // createdAt
type ArrayFields = PickByValue<User, string[]>; // tags

const strings: StringFields = { id: 'u1', name: 'Ada' };
const dates: DateFields = { createdAt: new Date('2026-01-01') };
const arrays: ArrayFields = { tags: ['core', 'edge'] };

// keyof over the picked type names the matching fields without their values
type DateKeys = keyof PickByValue<User, Date>;
const key: DateKeys = 'createdAt';

console.log(strings.id, strings.name);
console.log(dates.createdAt.toISOString().slice(0, 10));
console.log(arrays.tags.join(','), key);