在返回嵌套对象时,Typescript不返回嵌套类型

问题描述 投票:2回答:2

我希望我的函数返回嵌套类型的内容,但即使我们确定应该返回的类型它也不起作用。我们来看看例子:

type Content = {
    some: {
        extra: string;
        prop: number;
    },
    other: string,
    somenumber: number
}

const factory = (content: Content) => {
    return (key: keyof Content) => {
        return content[key];
    };
};

const content:Content = {
    some: {
        extra: "wow",
        prop: 123
    },
    other: "abc",
    somenumber: 999
};

const el = factory(content);
const some = el("some"); // good, I can pass only existing key as a string
console.log(some.extra); // error, can't reach "extra"

LIVE EXAMPLE

我希望“some”包含并提出“extra”和“prop”,但采取“extra”会抛出TypeScript。

typescript
2个回答
2
投票

使用泛型类型参数定义函数,以便Typescript可以正确推断类型:

const factory = (content: Content) => {
    return <K extends keyof Content>(key: K) => {
        return content[key];
    };
};

See this live example.


1
投票

修复非常简单:

const factory = (content: Content) => {
    return <T extends keyof Content>(key: T) => {
        return content[key];
    };
};

不同的是,现在我们将key的类型限制为传递字符串文字而不是任何Content密钥

© www.soinside.com 2019 - 2024. All rights reserved.