【问题标题】:Pass Object Key As Generic将对象键作为通用传递
【发布时间】:2019-08-27 18:26:35
【问题描述】:

在 TypeScript 中,是否可以将对象中的每个键作为泛型传递给该对象中的每个对应值?例如:

interface Items
{
    [key: Key extends string]: Item <Key>;
};

interface Item <Key>
{
    name: Key;
};

如果键是字符串字面量,这可以实现:

type Name = 'a' | 'b' | 'c';

type Items =
{
    [Key in Name]?: Item<Key>;
};

interface Item <Name>
{
    name: Name;
};

const items: Items =
{
    // Type valid
    a:
    {
        name: 'a'
    },
    // Type error
    b:
    {
        name: 'c'
    }
};

我不确定如何扩展它以允许任何字符串。任何帮助将不胜感激。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你有一个从键类型计算值类型的泛型类型:

    interface Item<Key> {
        name: Key;
    };
    

    给定一个集合,即您的 Name 键类型,您可以计算整体对象类型。那么为什么不将Name 设为通用呢?

    type Items<Name extends string> = {
        [Key in Name]?: Item<Key>;
    };
    

    现在您要验证给定类型(即对象字面量的类型)是否符合Items 约束。即是否存在类型Name,使得对象字面量的类型正好是Items。 TypeScript 中没有直接形成存在类型,但这可以通过函数参数的推断来完成:

    function checkType<Name extends string>(items: Items<Name>): Items<Name> {
        return items;
    }
    

    像这样使用它:

    const items = checkType({
        a: {
            name: 'a',
        },
        b: {
            name: 'c', // cannot pass the check
            // name: 'b', // passes the check
        },
    });
    

    【讨论】:

    • 谢谢。这是一个有趣的解决方案。不幸的是,它需要使用一个函数。如果没有其他选择,可能不得不接受,但最好避免这样做。
    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 2014-08-24
    • 2015-12-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    相关资源
    最近更新 更多