undefined
undefined

Reputation: 6844

Typescript how to return the correct type from a function

I have a function that returns string or number. I want typescript to automatically determine the returned value based on my if statement. How can I do this?

function isString(value): boolean {
    return typeof value === 'string';
}

function something(val) : string | number {
    if (isString(val)) {
        return 'string';
    }

    return 1;
}

const v = something(1);

v type is string | number, I want it to be a number in this case.

Upvotes: 1

Views: 51

Answers (2)

Alessandro
Alessandro

Reputation: 4472

Exactly as you done... see following TypeScript please:

class Test {
    isString (value: any): boolean {
        return typeof value === 'string'
    }

    something (val: any): string | number {
        if (this.isString(val)) {
        return 'string'
        }
        return 1
    }
}

let test = new Test()
console.log(typeof test.something("A"))
console.log(typeof test.something(1))

It compiles in something like:

var Test = /** @class */ (function () {
    function Test() {
    }
    Test.prototype.isString = function (value) {
        return typeof value === 'string';
    };
    Test.prototype.something = function (val) {
        if (this.isString(val)) {
            return 'string';
        }
        return 1;
    };
    return Test;
}());
var test = new Test();
console.log(typeof test.something("A"));
console.log(typeof test.something(1));

And if you run it... you can see that it returns a string or a number as you expected.

I hope it helps you, bye.

Upvotes: 0

Tao
Tao

Reputation: 2242

You can use overload method definitions. When you provide multiple method signatures, the last one is the actual implementation and TypeScript will hide its signature.

function something(val: string): string;
function something(val: any): number;
function something(val: any): string | number {
    if (isString(val)) {
        return 'string';
    }

    return 1;
}

Upvotes: 2

Related Questions