【问题标题】:Get type of sibling parameter获取兄弟参数的类型
【发布时间】:2020-07-30 08:48:30
【问题描述】:

我正在编写一个图形组件,该组件具有xy 轴的配置。 我希望像这样使用GraphProps

type Stock = {
  timestamp: string;
  value: number;
  company: 'REDHAT' | 'APPLE' | ... ;
}

const props: GraphProps<Stock> = {
  x: {
    dataKey: 'timestamp',
    // type-checks that timestamp is a string
    formatText: timestamp => new Date(timestamp).toDateString()
  },
  y: {
    dataKey: 'company',
    // type-checks that company is 'APPLE' | 'REDHAT' | ...
    formatText: company => company === 'APPLE' ? 'Apple' : company
  }
}

我有以下打字稿代码:

type AxisType<T> = {
  dataKey: keyof T;
  // i want point to be:
  // T[dataKey]
  // how can I access dataKey from within the formatText
  // type definition?
  formatText: (point: T[keyof T]) => string;
}

type GraphProps<T> = {
  x: AxisType<T>;
  y: AxisType<T>;
}

但是,对于当前定义,formatText 类型是 Stock[keyof Stock],它等于 Stock['timestamp' | 'value' | 'company'],当我想要的是,如果提供的 dataKeycompany,我希望 formatText 类型是Stock['company']

我想用 2 个类型参数 (GraphProps&lt;T, XDataKey, YDataKey&gt;) 扩展 GraphProps 泛型类型,但是我可能会添加两个以上的轴和/或动态添加更多的轴。

【问题讨论】:

    标签: javascript reactjs typescript typescript-generics


    【解决方案1】:

    像这样定义AxisType&lt;T&gt;GraphProps&lt;T&gt;

    type AxisType<T> = {
      [K in keyof T]: {
        dataKey: K;
        formatText: (point: T[K]) => string;
      };
    }[keyof T];
    
    type GraphProps<T> = {
      [axis: string]: AxisType<T>;
    };
    

    【讨论】:

    • 我只是在编译器自动推断 T 时遇到问题,即没有在 Graph&lt;Stock&gt; 中传递 Stock,如果您有任何可以帮助编译器的想法。跨度>
    • @Henke 除非你有一个类型为Stock 的值或一个类型的值是Stock 在你初始化props 时的容器,否则没有办法得到GraphProps推断T.
    • 我想我的问题表述有误,我的意思是,我可以在不显式传递类型参数的情况下做到这一点。我有一个const stocks: Stock[],假设GraphProps 有一个附加属性data: T[],我将我的Graph 组件初始化为:&lt;Graph data={stocks} x={...} y={...}/&gt;,以便编译器从data 属性推断T。但是现在我必须写:&lt;Graph&lt;Stock&gt; data={stocks} x={...} y={...}/&gt;,这绝对不错!但如果有办法让它自动推断它会更好。现在推断的类型是never :P
    • @Henke type GraphProps&lt;T&gt; = { data: T[]; x: AxisType&lt;T&gt;; y: AxisType&lt;T&gt;; }; 没有按你想要的方式工作?
    • 它确实按照我想要的方式工作,只是当我更新 AxisType 定义并使用你的定义时,Typescript 编译器没有正确推断出 T 参数。我不知道为什么,它没有正确推断,需要我传递类型参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2021-02-25
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多