我正在try 创建一个泛型函数,它只适用于扩展为string[]
的对象类型中的属性.例如,对象类型可能是:
type Thing = {
a: Thing2[],
b: Thing3[],
c: number,
}
const thing2 = ['!', '@', '#'] as const;
type Thing2 = typeof thing2[number];
const thing3 = ['1', '2', '3'] as const;
type Thing3 = typeof thing3[number];
并且该功能将仅接受键a
和b
.
删除了所有不相关的代码后,到目前为止,我有:
type KeysMatching<T, V> = {[K in keyof T]-?: T[K] extends V ? K : never}[keyof T];
function append<O extends object, K extends KeysMatching<O, string[]>>(
obj: O,
key: K,
item: O[K] extends (infer U)[] ? U : never
) {
obj[key].push(item); // Property 'push' does not exist on type 'O[K]'
}
但TypeScrip似乎没有意识到obj[key]
是string[]
类型的.如果可能的话,我也想避免使用as
这个关键字.