Closed
Description
🔎 Search Terms
"class", "conditinal types", "conditional functions parameters", "optional function parameters"
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about classes
⏯ Playground Link
💻 Code
class TestClass<TInput> {
// Type '(args?: TInput) => void' is not assignable to
// type 'TInput extends undefined ? (args?: TInput | undefined) => void : (args: TInput) => void'
foo: TInput extends undefined
? (args?: TInput) => void
: (args: TInput) => void
= (args?: TInput): void => {}
}
const optional = new TestClass<undefined>();
optional.foo(); // OK, as expected
const required = new TestClass<number>();
required.foo(); // Error, argument for args was not provided, as expected
required.foo(1); // OK, as expected
// It appears to work outside of class context
type Opt<T> = (args?: T) => void;
type Req<T> = (args: T) => void;
const a: Opt<number> = (args?: number) => {};
const b: Req<number> = (args?: number) => {};
type Check<T> = T extends undefined ? Opt<T> : Req<T>;
const c: Check<undefined> = (args?: number) => {};
const d: Check<number> = (args?: number) => {};
// You can wrap as any on the initial value
class TestClass2<TInput> {
// Type '(args?: TInput) => void' is not assignable to type 'Check<TInput>'.
bar: Check<TInput> = (args?: TInput) => {}
baz: Check<TInput> = ((args?: TInput) => {}) as any
}
const optional2 = new TestClass2<undefined>();
optional2.bar(); // OK, as expected
optional2.baz(); // OK, as expected
const required2 = new TestClass2<number>();
required2.bar(); // Error, argument for args was not provided, as expected
required2.baz(); // Error, argument for args was not provided, as expected
required2.bar(1); // OK, as expected
required2.baz(1); // OK, as expected
🙁 Actual behavior
class TestClass<TInput> {
// Type '(args?: TInput) => void' is not assignable to
// type 'TInput extends undefined ? (args?: TInput | undefined) => void : (args: TInput) => void'
foo: TInput extends undefined
? (args?: TInput) => void
: (args: TInput) => void
= (args?: TInput): void => {}
}
🙂 Expected behavior
class TestClass<TInput> {
// This should be possible
foo: TInput extends undefined
? (args?: TInput) => void
: (args: TInput) => void
= (args?: TInput): void => {}
}
I would expect this to work because it works outside of class definitions, and because having the implementation function args
be optional should be able to handle both cases.
Additional information about the issue
Might be related to #12400