是否有可能使所有REST参数都成为可选参数?
function thisIsAfunction<TArgs extends unknown[] = []>(callback: (firstParam: string, ...args: TArgs) => void) {
/* Do something */
}
// This is okay ✅
thisIsAfunction((type: string, name?: string, id?: number) => {});
// This should cause a type error ❌
// (is it possible to force all args to be optional?)
thisIsAfunction((type: string, name: string, id: number) => {});
以下是扩展的示例:
type SelectCommand<TArgs extends unknown[]> = (filter: any, ...args: TArgs) => void;
class DataSource<TSelectArgs extends unknown[] = []> {
select: SelectCommand<TSelectArgs>;
constructor(config: {select: SelectCommand<TSelectArgs>}) {
this.select = config.select;
}
}
const ds = new DataSource({
// This should cause a type error for id and type because they are not optional
// Is it possible to force the rest arguments to be optional?
select: (filter: any, id: number, type: string) => { /* Do something */ }
})
ds.select('Search', 1, 'type'); // This should work
ds.select('Search'); // And this should always work