Open 981377660LMT opened 2 years ago
如果需要在某个接口扩展自定义属性 优先考虑联合类型而不是索引签名 因为索引签名没有类型提示
export interface WindowManager<T, Q> { add(value: T, index: number, qLeft: number, qRight: number): void remove(value: T, index: number, qLeft: number, qRight: number): void query(): Q }
export function useMoAlgo<T = number, Q = number>(windowManager: WindowManager<T, Q>) {...}
![索引签名](https://user-images.githubusercontent.com/45849137/182904754-f929f11e-a22f-4f82-b352-bb014ea3bb61.png) - 联合类型有类型提示 (注意这里还是需要加上索引签名来防止ts检测属性不存在的报错) ```ts export interface WindowManager<T, Q> { add(value: T, index: number, qLeft: number, qRight: number): void remove(value: T, index: number, qLeft: number, qRight: number): void query(): Q [other: string]: unknown } export function useMoAlgo<T = number, Q = number, R = object>( windowManager: WindowManager<T, Q> & R ) {...}
注意上面这种方法还不完善
标题应该为: typescript怎么识别动态添加的对象属性
如果需要在某个接口扩展自定义属性 优先考虑联合类型而不是索引签名 因为索引签名没有类型提示
export function useMoAlgo<T = number, Q = number>(windowManager: WindowManager<T, Q>) {...}