【发布时间】:2018-10-26 15:02:04
【问题描述】:
我有一个接收对象的工厂函数,如果该对象具有特定名称的属性,工厂会将这些属性转换为方法。
如何使用映射类型正确表示输出对象的类型?
例如,假设可转换属性为 foo、bar、baz:
interface IFactoryConfig {
foo?: string;
bar?: string;
baz?: string;
}
替换属性为:
interface IFactoryResult {
foo(someParam: string): boolean;
bar(): number;
baz(otherParam: number): void;
}
如果输入的类型是
interface IInputObject {
baz: string;
notPredefined: string;
aNumber: number;
foo: string;
aMethod(): void;
}
工厂用方法替换baz和foo并返回:
interface IInputObject {
baz(otherParam: number): void;
notPredefined: string;
aNumber: number;
foo(someParam: string): boolean;
aMethod(): void;
}
我正在尝试使用映射类型来替换属性:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
interface IFactory {
<InputType extends IFactoryConfig, ResultType>(config: InputType): Omit<InputType, keyof IFactoryConfig> & Pick<IFactoryResult, ?>;
}
我不知道在 Pick 中放入什么以从 IFactoryResult 中选择也出现在 InputType 上的属性。
【问题讨论】: