简体   繁体   中英

Typescript return type based on argument with types not function overloading

So im trying to make a single function GetSet, with 2 args, one is the index, and the other one is a value, if the value is not given, the func should return a value (get), if it is given it should return nothing (set). I know i can do something like this using function overloading which works.

function GetSet<T>(i: number):T
function GetSet<T>(i: number, val: T):void
function GetSet<T>(i: number, val?: T): T | void {
    if (val === undefined)
        return 1 as unknown as T // just an example
    else 
        return
}

const returnsNumber = GetSet<string>(1)
const returnsVoid   = GetSet<string>(1, 'test')

But i need it in a generic type way so i tried this,

type GetSetType<T> = {
    <T>(i: number) : T
    <T>(i: number, val: T) : void
    <T>(i: number, val?: T | undefined) : T | void
}

const test: GetSetType<number> = (i: number, val?: number) => {
    if (val === undefined)
        return 1
    else 
        return
}

But it doesnt work, what am i doing wrong?

const returnsUnknown = test(1)

Figured out why, the T in GetSetType<T> and T in each function are recognized as completely different things. So i gotta use something like this.

type GetSetType<T> = {
    <U extends T>(i: number) : U
    <U extends T>(i: number, val: T) : void
    <U extends T>(i: number, val?: T | undefined) : U | void
}

const test: GetSetType<number> = (i: number, val?: number) => {
    if (val === undefined)
        return 1
    else 
        return
}

const returnsNumber = test(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM