Can I mark the parameter in a TypeScript function to be optional by a special type without question mark?

Viewed 126

In general I could make a function have an optional argument as:

function func1(foo:number, bar?:string) : void {}

Now I'd like to make a generic function in which the type of the second argument depends on what the first is:

type Magic<T> = T extends SomeCondition ? T : never;

function func1<T>(foo:T, bar:Magic<T>) : void {}

Obviously the Magic type can't control the ? mark before :.

It could only make the type of the argument bar to be never under some cases but the argument is always required.

Can I make the second argument to be optional by a special type or any other way?


UPDATE:

A complete sample:

class A {
    public foo:string = ''
}

type Test<T> = T extends A ? number : never

function func<T>(arg1 : T, arg2: Test<T>) {

}

// I want the second argument to be required
// if the first is subtype of class A
func({ foo: 'bar'}, 10); 
// Otherwise I want the second argumtn to be optional
// However, error happens here: `Expected 2 arguments, but got 1`  
func({ other: 'bar'});   
1 Answers
Related