Using Typescript function overloading for better clarity:
function process(request: true): Promise<string>;
function process(request: false): Promise<number>;
function process(request: boolean) {
return new Promise((resolve, reject) => {
if (request)
resolve("something");
resolve(1);
});
}
process(true).then(result => {
console.log(result.length); //<-- correctly identifies result as a string
});
process(false).then(result => {
console.log(result.length); //<-- error: property 'length' does not exist on type number
});
Typeguards are important to use within if
statements.
UPDATE
An interesting fact! Typescript also supports overloading distinction based on fields. See the code snippet below:
function process(options: { request: true }): Promise<string>;
function process(options: { request: false }): Promise<number>;
function process(options: { request: boolean }) {
return new Promise((resolve, reject) => {
if (options.request)
resolve("something");
resolve(1);
});
}
process({ request: true }).then(result => {
console.log(result.length); //<-- recognizes that result is a string
});
process({ request: false }).then(result => {
console.log(result.length); //<-- error: property length cannot be found on type number
});
UPDATE
By using generics, you can achieve the desired behavior. In this way, only the request
field matters from the caller's perspective. However, there may be a loss of typecheck even for options.request
within the implementation of the process
functions.
function process<T extends { request: true }>(options: T): Promise<string>;
function process<T extends { request: false }>(options: T): Promise<number>;
function process(options: any) {
return new Promise((resolve, reject) => {
if (options.request)
resolve("something");
resolve(1);
console.log(options.anything);
});
}
process({ request: true, foo: 'bar' }).then(result => {
console.log(result.length); //<-- correctly identifies result as a string
});
process({ request: false, foo: 'baz' }).then(result => {
console.log(result.length); //<-- error: property length cannot be found on type number
});