Home > Software design >  TypeScript make function output dependent on whether an input parameter is undefined or not
TypeScript make function output dependent on whether an input parameter is undefined or not

Time:04-17

I have a function that takes an optional object as a parameter which has a key called initialData. The function does some processing and returns an object that contains a data key which can be undefined or can be of the generic type passed to the function.

Now what I want is that when initialData is provided to the options data would never be undefined in the output.

Here is a contrived example of what I was able to figure out so far, but it's not working as expected:

interface Options<Data = unknown> {
    initialData?: Data;
    prop1?: string;
}

interface OptionsWithInitialData <Data = unknown> extends Options<Data> {
    initialData: Data;
}

interface Result<Data = unknown> {
    data?: Data;
    key: string;
}

interface ResultWithData<Data = unknown> extends Result<Data> {
    data: Data;
}

type PossibleOptions<Data> = Options<Data> | OptionsWithInitialData<Data>;

function doSomething<Data, TOptions extends PossibleOptions<Data>>(key: string, options?: TOptions): TOptions extends OptionsWithInitialData<Data> ? ResultWithData<Data> : Result<Data> {
    return {
        data: options?.initialData,
        key,
    }
}

const result = doSomething('test', { initialData: { foo: 'bar' } })

// This should not throw an error
console.log(result.data.foo)

export { doSomething };

Also here is a enter image description here

So technically I guess your conditional type would work, but since TData of your return type is unknown, you can't really use it.

The difference to useQuery hook is that TypeScript there can automatically infer the TData type from the query functions return type.

  • Related