This works:
type OptionalInit = void | string
function foo(url: string, init: OptionalInit) {
console.log(url)
}
foo("hello", "world")
foo("hello")
This works:
type lookup = {
"a": void | string
}
function foo2(url: string, init: lookup["a"]) {
console.log(url)
}
foo2("hello", "world")
foo2("hello")
But this doesn’t work:
type lookup = {
"a": void | string
}
function foo3<T extends keyof lookup>(url: string, init: lookup[T]) {
console.log(url)
}
foo3<"a">("hello", "world")
foo3<"a">("hello")
test.ts:33:1 - error TS2554: Expected 2 arguments, but got 1.
33 foo3("hello")
~~~~
test.ts:28:52
28 function foo3<T extends keyof lookup>(url: string, init: lookup[T]) {
~~~~~~~~~~~~~~~
An argument for 'init' was not provided.
What gives? Is this a bug with tsc?
For context, I’m trying to make a function with a conditionally optional second parameter. My idea was to just do a generics lookup to determine whether second parameter should be optional (by adding the | void
:
type lookup = {
"a": void | string,
"b": string
}