【问题标题】:TypeScript: Generic type for interface with one required fieldTypeScript:具有一个必填字段的接口的通用类型
【发布时间】:2020-08-28 12:06:32
【问题描述】:

我想创建一个函数f,它接受一个字符串并创建一个对象,其中key 是唯一的字段集。

我还希望函数对接口A 进行类型检查,以确保key-字段是对象上唯一的必需字段。 (会有其他可选字段)。

问题:

是否可以表达A 类型以使函数f 有效——并且不会产生类型错误——并且在使用时仍然正确地对A 进行类型检查?

export function f<A extends { key: string }>(key: string): A {
  return { key }; // This produces compile error TS2322: (see below)
}

// This be a few different interfaces, but they all have in common that
// the key-field is the only required field.
interface WithKey {
  key: string;
  ignoreMe?: string;
}

const result = f<WithKey>('myKey');

编译器错误:

TS2322:键入'{键:字符串; }' 不可分配给类型 'A'。 '{键:字符串; }' 可分配给“A”类型的约束,但“A”可以用约束“{ key: string;”的不同子类型来实例化。 }'。

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    问题是您的语句说它接受必须具有keystring 的类型,并且该类型将被返回。

    这意味着如果我经过那里

    {key: 1, requiredField: 5}
    

    它返回与 requiredField 相同的类型。

    但是实现 return { key } 打破了这个声明,因为它不再返回 requiredField。这会导致 TS2322。

    一个可能的解决方案 - 简单地说你返回的界面。

    export function f(key: string): { key: string } { // <- return type
      return { key };
    }
    
    interface WithKey {
      key: string;
      ignoreMe?: string;
    }
    
    const result: WithKey = f('myKey');
    
    result.key; // works
    result.ignoreMe // works (undefined)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多