San*_*Ben 5 typescript typescript-generics
是否可以将所有其余参数设为可选?
\nfunction thisIsAfunction<TArgs extends unknown[] = []>(callback: (firstParam: string, ...args: TArgs) => void) { \n /* Do something */ \n}\n\n// This is okay \xe2\x9c\x85\nthisIsAfunction((type: string, name?: string, id?: number) => {});\n\n// This should cause a type error \xe2\x9d\x8c\n// (is it possible to force all args to be optional?)\nthisIsAfunction((type: string, name: string, id: number) => {});\nRun Code Online (Sandbox Code Playgroud)\n\n这是扩展的示例:
\ntype SelectCommand<TArgs extends unknown[]> = (filter: any, ...args: TArgs) => void;\nclass DataSource<TSelectArgs extends unknown[] = []> {\n select: SelectCommand<TSelectArgs>;\n constructor(config: {select: SelectCommand<TSelectArgs>}) {\n this.select = config.select;\n }\n}\n\nconst ds = new DataSource({\n // This should cause a type error for id and type because they are not optional\n // Is it possible to force the rest arguments to be optional?\n select: (filter: any, id: number, type: string) => { /* Do something */ }\n})\n\nds.select(\'Search\', 1, \'type\'); // This should work\nds.select(\'Search\'); // And this should always work\nRun Code Online (Sandbox Code Playgroud)\n\n
据我所知,只需输入其余参数似乎就undefined[]可以解决问题:
function thisIsAfunction<TArgs extends undefined[] = []>(callback: (firstParam: string, ...args: TArgs) => void) { \n// \xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^^^^^^^^^\n /* Do something */ \n}\n\n// This is okay \xe2\x9c\x85\nthisIsAfunction((type: string, name?: string, id?: number) => {});\n\n// This should cause a type error \xe2\x9d\x8c\n// (is it possible to force all args to be optional?)\nthisIsAfunction((type: string, name: string, id: number) => {});\nRun Code Online (Sandbox Code Playgroud)\n\n对于问题的扩展版本,您可以使用映射元组(在本例中名为Optionalized):
type Optionalized<T> = { [K in keyof T]: T[K] | undefined };\n\ntype SelectCommand<TArgs extends unknown[]> = (filter: any, ...args: Optionalized<TArgs>) => void;\n\nclass DataSource<TSelectArgs extends unknown[] = []> {\n select: SelectCommand<TSelectArgs>;\n constructor(config: {select: SelectCommand<TSelectArgs>}) {\n this.select = config.select;\n }\n}\n\nconst ds = new DataSource({\n select: (filter: any, id?: number, type?: string) => { /* Do something */ }\n})\n\nds.select(\'Search\', 1, \'type\'); // This should work\nds.select(\'Search\'); // And this should always work\nRun Code Online (Sandbox Code Playgroud)\n\n正如 @SanBen 在评论中指出的,Optionalized上面示例中的类型也可以替换为 TypeScript\ 的Partial实用程序类型。
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |