1

it's possible to compile code with this intent:

type Tick = Date | number;

type Unary<T, R> = (_: T) => R;

function formatter<T extends Tick>(tick: T): Unary<T, string> {
    if (tick instanceof Date) {
        return (date: Date) => date.toUTCString();
    }
    return (int: number) => int.toFixed();
}

playground link

My idea is that if T is Date, tick is Date and return type is Unary<Date, string>, but Typescript tries it to unify with Unary<T, string>. It is because T extends Tick is broader than just Tick union? If so, can I limit this generic?

2
  • 5
    What do you expect to happen when someone calls formatter(someExpr) when someExpr is of type Date | number ? Commented Jan 22, 2019 at 16:01
  • Didn't think about that...
    – dhuCerbin
    Commented Jan 22, 2019 at 16:17

1 Answer 1

3

Don't think you can narrow the type of a parameter that is of a generic type. Any type gard will still preserve the type parameter in there as the compiler assumes a type parameter can be any derived type, so it can't eliminate what it does not know for certain.

Also what you are trying to do is narrow all type parameter occurrences (ie the occurrence in the return type) based on the check on the parameter which is definitely not possible. Type guards work on the specific variable not on the type as a whole.

One option is to use a separate implementation signature:

type Tick = Date | number;

type Unary<T, R> = (_: T) => R;

function formatter<T extends Tick>(tick: T): Unary<T, string> 
function formatter(tick: Tick): Unary<Date, string> | Unary<number, string> {
    if (tick instanceof Date) {
        return (date: Date) => date.toUTCString();
    }
    return (int: number) => int.toFixed();
}
1
  • 3
    Stackoverflow's typescript God to the rescue again, thanks for this Titian Commented May 26, 2019 at 10:47

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.