繁体   English   中英

从字符串参数推断返回类型

[英]Infer return type from string parameter

假设我有一个 function 有点像这样

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;
}

如果我这样使用

const obj = getObjectFromString('foo');

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

obj的类型是{ loading: boolean, [key: string]: any}有没有什么办法可以让 object 的类型是{ loading: boolean, foo: any}相反,对于任何给定的字符串值?

我浏览了 typescript 文档,没有找到任何有用的东西

我认为确保键的文字类型并将结果转换为正确的类型应该可行:

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);

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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