通过组合接口来创建具有可区分字段的类型?
这是我的代码:
/*
* Missing changeFn indicates delete
*/
type IChangeRequestPromiseProxy<TEntity extends IBaseEntity> =
| IUpdateRequestPromiseProxy<TEntity>
| IDeleteRequestPromiseProxy;
interface IUpdateRequestPromiseProxy<TEntity extends IBaseEntity> {
id: Id;
resolve(value: IPersistence<TEntity>): void;
reject(reason: any): void;
changeFn(entity: TEntity): IPersistence<TEntity>;
}
interface IDeleteRequestPromiseProxy {
id: Id;
resolve(value: void): void;
reject(reason: any): void;
changeFn(entity: never): never;
}
let promiseProxy: IChangeRequestPromiseProxy<TEntity> = { id, resolve, reject };
这是我得到的错误。要点似乎是Property 'changeFn' is missing in type
:
让promiseProxy:IChangeRequestPromiseProxy类型'{id: 串;解决:(值?:IPersistence | PromiseLike> |未定义)=> void;拒绝: (原因?:任意)=>无效; }'无法分配给type “ IChangeRequestPromiseProxy”。属性“ changeFn”为 缺少类型'{id:string;解决:(值?:IPersistence | PromiseLike> |未定义)=> void;拒绝: (原因?:任意)=>无效; }',但必须输入 'IUpdateRequestPromiseProxy'.ts(2322)Queue.service.ts(16, 5):在此处声明“ changeFn”。
为什么不起作用?
答案 0 :(得分:1)
changeFn(entity: never): never;
没有使属性changeFn
成为可选属性。要使其可选,您可以使用?
对其进行声明,并且由于您实际上不需要此处的任何值,因此其类型应为undefined
从您的问题中添加缺少的类型看起来像:
type IChangeRequestPromiseProxy<TEntity extends IBaseEntity> =
| IUpdateRequestPromiseProxy<TEntity>
| IDeleteRequestPromiseProxy;
interface IUpdateRequestPromiseProxy<TEntity extends IBaseEntity> {
id: Id;
resolve(value: IPersistence<TEntity>): void;
reject(reason: any): void;
changeFn(entity: TEntity): IPersistence<TEntity>;
}
interface IDeleteRequestPromiseProxy {
id: Id;
resolve(value: void): void;
reject(reason: any): void;
changeFn?:undefined;
}
interface IBaseEntity {}
class Entity { }
interface IPersistence<T> { o: T}
type Id = string;
declare const id: string;
declare const resolve: (value: void) => void;
declare const reject: (value: any) => void;
let promiseProxy: IChangeRequestPromiseProxy<Entity> = { id, resolve, reject };