0

Given this function:

myFunc(object: string | null): string | null {}

I would like this function to be of return type string when the object is string, and return type of string | null when the object is of type string | null.

I have tried:

myFunc<T extends string | null>(object: T): T {
    return "returnValue"; //Type '"returnValue"' is not assignable to type 'T'.
}

and

myFunc<T extends string & null>(object: T): T {
    return "returnValue"; //Type '"returnValue"' is not assignable to type 'T'.
}

Both produce the same compile error. I have not found the correct syntax to do this.

1 Answer 1

7

I can't believe I'm actually going to suggest overloads, as I spend a goodly portion of my time explaining how most of them can be avoided... but an overload would be a good way to model this!

class Example {
    myFunc(obj: string): string;
    myFunc(obj: string | null): string | null;
    myFunc(obj: string | null): string | null {
        return "returnValue";
    }
}

function test(a: string | null, b: string) {
    const example = new Example();

    // resultA: string | null
    const resultA = example.myFunc(a);

    // resultB: string
    const resultB = example.myFunc(b);
}

In the above example, the return types are mapped to the input types, so resultA and resultB have the expected types, provided you are running with strict null checks enabled.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.