【问题标题】:In Typescript, it is possible to add properties keys using generics?在 Typescript 中,可以使用泛型添加属性键吗?
【发布时间】:2018-05-30 07:01:40
【问题描述】:

在打字稿中,可以使用泛型添加属性键吗?

function f<T extends string>(k: T) {
  return { [k]: 'test'; };
}

const obj = f('foo');
// some how assert that obj.foo exists

我有一个类似上面的函数,它接受一个键 k 并使用 {[identifier]: 'value'} 动态地将该键添加到一个对象。


我想知道是否可以捕获字符串文字类型,例如'some-key'/T extends string 并在另一种类型中使用文字。像这样的:

interface F<T extends string> {
  [T]: SomeRandomType;
  otherKey: string;
  anotherKey: number;
}

interface SomeRandomType { /* ... */ }

const f: F<'bar'> = /* ... */;
f.otherKey; // should work
f.anotherKey; // should work
f.bar; // should work

有什么想法吗?这不可能吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    是的,这可以通过 mapped typesintersection types 的创意组合来实现。

    您可以使用映射类型对“任意字符串文字键属性”的情况进行建模。

    type F<Keys extends string> = {
        [K in Keys] : number;
    }
    
    const f : F<'bar'> = null;
    f.bar;  // typed as a number
    f.wibble;  // type error
    

    请注意,映射类型必须是 type 声明,而不是 interfaces。不要问我有什么区别!

    然后是使用交集类型运算符&amp; 将附加属性分层的情况。出于某种原因,您必须为此使用&amp;。您似乎不允许将这些属性声明为同一对象类型的一部分。

    type F<Keys extends string> = {
        [K in Keys] : number;
    } & {
        additionalKey1 : object;
        additionalKey2 : string;
    }
    const f : F<'bar'> = null;
    f.bar;  // typed as a number
    f.additionalKey1;  // typed as an object
    

    【讨论】:

      猜你喜欢
      • 2011-03-22
      • 2021-02-11
      • 2020-02-14
      • 2022-01-07
      • 2020-04-12
      • 2020-05-17
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多