实现说明
模块级对象字面量,键名固定: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);