显然,在打字稿中,可选参数和未定义的联合类型参数之间存在差异
function test(s: string|undefined) {}
function test2(s?: string) {}
test() // error: An argument for 's' was not provided
test2() // OK
Run Code Online (Sandbox Code Playgroud)
我想声明一个泛型函数,根据提供的类型,其参数是可选的或必需的。例如:
// Intention: if type is the same as its Partial counterpart then the parameter can be made optional
type MaybeOptional<T> = Partial<T> extends T ? T|undefined : T
type O = {
name?: string
}
function generic<T extends any>(t: MaybeOptional<T>) {}
generic<O>({name:""})
generic<O>() // error. An argument for 't' was not provided.
Run Code Online (Sandbox Code Playgroud)
我如何在 Typescript 中表达这样的意图?我可以通过泛型分配这个“可选”特征吗?