【问题标题】:Can I somehow define what can be the indexed name in the interface based on another interface in TypeScript?我可以基于 TypeScript 中的另一个接口以某种方式定义接口中的索引名称吗?
【发布时间】:2020-04-01 16:44:46
【问题描述】:

我有这个interface

export interface FieldContainerInterface {
  [key: string]: FieldInterface;
}

我想基于另一个接口定义key 字符串。我希望使用这样的东西:

interface FieldContainerInterface<T> {
  // in here how can I pick the fields from <T>?
  [T<key>: string]: FieldInterface;
}

interface BanknoteInterface {
  id: number;
  deviza_id: number;
  value: string;
}

class Banknote implements BanknoteInterface {
  id: number;
  deviza_id: number;
  value: string;

  fieldContainer: FieldContainerInterface<BanknoteInterface> {
    // here I MUST to define id, defiza_id and value fields
  }

我能否以某种方式定义FieldContainerInterface 中的key 字符串?

【问题讨论】:

    标签: typescript interface typescript-generics


    【解决方案1】:

    您可以为此使用mapped type

    type FieldContainerInterface<T> = {
        [key in keyof T]: FieldInterface;
    }
    

    Playground

    【讨论】:

      【解决方案2】:

      不确定您想要实现的具体目标,但将键限制为某些值的一种方法是使用 keyof 运算符。 Here 是一篇关于它的好文章。示例:

      import React from 'react';
      
      interface BanknoteInterface {
        id: number;
        deviza_id: number;
        value: string;
      }
      
      type FieldContainerInterface<T> = {
        [key in keyof T]?: any;
      }
      
      
      
      class Banknote implements BanknoteInterface {
        id: number;
        deviza_id: number;
        value: string;
      
        fieldContainer: FieldContainerInterface<BanknoteInterface> = {
          // optionally add any key
          value: "hello",
          // id: 5,
          // deviza_id: 5
        }
      }
      

      文档: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

      【讨论】:

        猜你喜欢
        • 2018-12-01
        • 1970-01-01
        • 2011-02-22
        • 2012-10-16
        • 2023-01-10
        • 1970-01-01
        • 2019-08-31
        • 2013-08-14
        • 1970-01-01
        相关资源
        最近更新 更多