I have a class method declaration with three parameters:
declare class Application {
PrintOut(OutputFileName?: string, PrintToFile?: boolean, StartPage?: number): void;
}
When printing to a file, the output file name must be passed; when not printing to a file, the filename cannot be passed. This means that the OutputFileName
parameter's type depends on the PrintToFile
parameter, as follows:
- If
PrintToFile
istrue
, thenOutputFileName
is of typestring
and notundefined
-- i.e. not optional. - Otherwise (
PrintToFile
isfalse
/undefined
, or not passed), thenOutputFileName
must beundefined
Or, using overloads:
declare class Application {
PrintOut(OutputFileName: string, PrintToFile: true, StartPage?: number): void;
PrintOut(OutputFileName?: undefined, PrintToFile?: false, StartPage?: number): void;
}
the following calls are valid:
x.PrintOut('abcd', true);
x.PrintOut(undefined, false);
x.PrintOut(undefined, undefined);
x.PrintOut();
and the following calls are invalid:
x.PrintOut(undefined, true); // first parameter must be a string
x.PrintOut('abcd', false); // cannot pass a filename if not printing to a file
x.PrintOut('abcd', undefined); // (same as above)
x.PrintOut('abcd'); // (same as above)
How can I duplicate the functionality of the above overloads using conditional types?
If there were only the two parameters, I would stick with overloads. But this is just an MCVE. The actual method has 19 parameters, with multiple parameters depending on specific values of each of 3 different parameters; and similar methods are applied to 5 different object types.
Using this:
type IfPrintToFile<T, U> =
T extends true ? U :
undefined;
declare class Application {
PrintOut<T extends boolean>(OutputFileName?: IfPrintToFile<T, string>, PrintToFile?: T, StartPage?: number): void;
}
doesn't prevent these:
x.PrintOut(undefined, true);
x.PrintOut('abcd', undefined);
x.PrintOut('abcd');
while defining the constraint on the method as T extends boolean | undefined
still doesn't block these:
x.PrintOut(undefined, true);
x.PrintOut('abcd');
Defining the parameters as required:
type IfPrintToFile<T, U> =
T extends true ? U :
undefined;
declare class Application {
PrintOut<T extends boolean | undefined>(OutputFileName: IfPrintToFile<T, string>, PrintToFile: T, StartPage?: number): void;
}
blocks all the invalid calls, but also blocks the following valid call:
x.PrintOut();
1. It seems the Options settings are not stored in the Playground URL, and need to be set manually each time.
PrintOut()
why not just define an overload for that one case. Maybe conditional types can't get you to just one signature, but they might reduce the number of overloads. – Titian Cernicova-Dragomir Jul 24 '18 at 1:48