简体   繁体   中英

Infer return type from string parameter

Let's say I have a function somewhat like this

function getObjectFromString(str: string): { loading: boolean, [key: string]: any } {
    const result = {
        loading: false,
    };

    // Set the value of the key based on the input string
    result[str] = true;

    return result;
}

If I use use like this

const obj = getObjectFromString('foo');

// obj has the following properties:
// - loading: false
// - foo: true

The type of the obj is { loading: boolean, [key: string]: any} Is there any way I can make it so the type of the object is { loading: boolean, foo: any} instead, for any given string value?

I skimmed through the typescript docs, didn't find anything useful

I think ensuring a literal type for a key and casting the result to the right type should work:

type StringLiteral<T> = T extends string ? string extends T ? never : T : never;

function getObjectFromString<T extends string>(str: StringLiteral<T>) {
    return {
        loading: false,
        [str]: true,
    } as { [ x in T]: boolean } & { loading: boolean };
}

const obj1 = getObjectFromString('test1');
obj1.test1 = false;
obj1.test2 = 'error expected';
const test2: string = 'does not work';
const obj2 = getObjectFromString(test2);

Playground link

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