Typescript 类型定义
来源:2-1 什么是 Typescript

慕粉2243039935
2020-04-24
老师 我想问一个工作上的业务需求问题,不知道是否有空解答
就是在定义 interface的时候, Data 是一个数据源,数据格式为[{a: 1,b: 2},{a:1, b: 2}] 里面不定任何属性规范 就是一个 any[],
然后在 Position 里 是一个长度为2的元组 ,他的组成是由 Data 中 对象的属性组成,如 ['a', 'b'] 或者可以是 ['b','a'] ,但是不能为 ['a','c'] 因为 ‘c’不在 Data 数组中的对象属性里。 老师能帮忙解答下这种需求应该怎么实现吗?
这是我努力后的代码。。。但是不满足上面说的需求...望老师帮忙改正指点...,实在没办法了....
export interface BaseChartProp {
data: any[] // [{a: 1,b: 2},{a:1, b: 2}]
// ['a', 'b']
position: [keyof BaseChartProp['data'], keyof BaseChartProp['data']]
/** 自定义别名 */
// {'a': "", 'b': ""}
alias?: {
[P in keyof BaseChartProp['data']]: string
}
options?: {
[P in keyof ChartCfg]?: ChartCfg[P]
}
}
1回答
-
慕粉2243039935
提问者
2020-04-24
找到了一种方案
interface dataType {
[index: string]: any
}
export interface BaseChartProp<T extends dataType> {
data: T[] // [{a: 1,b: 2},{a:1, b: 2}]
// ['a', 'b']
position: [keyof T, keyof T]
/** 自定义别名 */
// {'a': "", 'b': ""}
alias?: {
[K in keyof T]: string
}
/** G2 Chart初始化选项 */
options?: {
[P in keyof ChartCfg]?: ChartCfg[P]
}
}
组件使用的时候
export function xxxChart<T>(props: BaseColumnChartProps<T>) {
}
<xxxChart data={[{a: '1', b: 'c'}]} position: ['a', 'b']>
暂时还没找到 以下这种写法,把 泛型给映射出去的方法。
export const xxxChart:FC<BaseColumnChartProps> = (props) => {
}
希望对遇到此问题的童鞋有些帮助~ 同时有更好的写法欢迎分享
012020-04-24
相似问题