想对Rule3的情况做更详细的类型推断,求解
export interface BaseOption {
required?:
| {
message?: string
tip?: string
}
| true
}
export type Validator = {
[key in string]?: (val: number, formData: string, callback, props) => void | Promise<void | Error>
}
export interface RequiredFunc {
required: (message: string) => void | Promise<void | Error>
}
export type CombineOptions<ExtraOption extends Validator> = ExtraOption & RequiredFunc
import { BaseOption, CombineOptions, Validator } from './type/index'
function Rule<ExtraOption extends Validator>(options: ExtraOption | BaseOption) {
return {} as ExtraOption extends BaseOption ? CombineOptions<ExtraOption> : ExtraOption
}
const rule1 = Rule({
a() {},
})
rule1.a // 有提示
const rule2 = Rule({ required: true })
rule2.required // 有提示
// 如果不手动加入Rule的泛型,下面的情况a没有代码提示
const rule3 = Rule({
a(f, b) {},
required: true,
})
rule3.required // 有提示
rule3.a // 无提示
已经解决了
https://stackoverflow.com/que...