TypeScript 2.1具有Mapped Types的强大功能,可以键入对象的键并通过键获取类型。例如,您可以更改原始对象的结构:
type FactoryUnit<T> = {
self: T;
};
type Factory<T> = {
compile: () => {[P in keyof T]: FactoryUnit<T[P]>};
clone: (mutator: (origin: T) => T) => Factory<T>;
};
function buildFactory<T>(v: T): Factory<T> {
return null;
}
const imp = buildFactory({ one: 1, two: 2 }).compile();
console.log(imp.one.self);
但是如果我想改变里面的物体怎么办?例如,我确信对象值具有modifiers
属性,我可以使用某些函数来使用它。
type FactoryUnit<T, M> = {
self: T;
modifiers: <R>(f: (v: M) => R) => R;
};
type Factory<T extends { [key: string]: { modifiers: M } }, M> = {
compile: () => {[P in keyof T]: FactoryUnit<T[P], T[P]['modifiers']>};
clone: (mutator: (origin: T) => T) => Factory<T, M>;
};
function buildFactory<T extends { [key: string]: { modifiers: M } }, M>(v: T): Factory<T, M> {
return null;
}
const imp = buildFactory({
one: { one: 1, modifiers: { mOne: 11 } },
two: { two: 2, modifiers: { mTwo: 11 } }
}).compile();
console.log(imp.one.modifiers(v => v.mOne)); // v is any
我试图告诉TypeScript关于modifiers
键,但是如何键入值以使ts推断它?如何告诉TypeScript modifiers
属性有M
类型?