0

I am developing a web application that uses cookies. To read a cookie I would like to write a typescript function of this type:

let cookie1: number = getCookie<number>("fake_int_name");
let cookie2: boolean = getCookie<boolean>("fake_bool_name");
let cookie3: string = getCookie<string>("fake_string_name");

function getCookie<T>(name: string): T {
    ...
    let cookie_value: string = "fake_cookie_value";

    if(T is number)
        return parseInt(cookie_value);

    if(T is boolean)
        return cookie_value == "true";

    return cookie_value;
}

Is it possible to create a getCookie function able of behaving differently depending on the type T?

1
  • 2
    No, types do not exist at runtime (erased at compile time) Commented Jan 27, 2021 at 11:57

1 Answer 1

1

First of all, interfaces only exist at compile time, so it is not possible to have conditions on them in the code.

Conditional return types do exist, but only seem to be partially supported:


enum ResultType {
    INT = 'int',
    BOOL = 'bool',
    STRING = 'string',
}

interface TypeMap {
    int: number;
    bool: boolean;
    string: string;
}

function getCookie<K extends ResultType>(name: string, type: K): TypeMap[K] {
    let cookieValue;
    // ...

    switch (type) {
        case ResultType.INT:
            return parseInt(cookieValue, 10) as any;
        case ResultType.BOOL:
            return (cookieValue === 'true') as any;
        case ResultType.STRING:
            return cookieValue as any;
    }
}


// usage:
getCookie('foo', ResultType.INT); // compiler correctly assumes number as return type
getCookie('foo', ResultType.BOOL); // compiler correctly assumes boolean as return type

You can see here that the return type is casted to any. The compiler does not properly infer this type. The issue addressing this is https://github.com/microsoft/TypeScript/issues/24929, but it seems to be closed without a fix.

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.