对象中的Typescript typeof值

时间:2019-01-28 08:56:19

标签: reactjs typescript

试图强力键入数据格式化功能。函数的作用很简单,

输入:

run --args='-h'

输出:

const eleOfArray = {
  a: 1,
  b: "string",
  c: [1, 2, 3]
}

功能:

const eleOfArray = {
  a: {
    value: 1,
    component: 1
  },
  b: {
    value: "string",
    component: "string"
  },
  c: {
    value: [1, 2, 3],
    component: [1, 2, 3]
  }
}

接口:

export function tableDataFormatter<T>(d: T) {
	const formatedData: ITableData<T> = {}

	Object.keys(d).forEach((key: string) => {
		// tslint:disable-next-line:ban-ts-ignore
		// @ts-ignore
		formatedData[key] = {
			// tslint:disable-next-line:ban-ts-ignore
			// @ts-ignore
			value: d[key as keyof T],
			component: d[key as keyof T]
		}
	})

	return formatedData
}

此代码的问题是,当我使用interface ITableData<T> { readonly [key: keyof T]: { readonly component: React.ReactNode readonly value: T[keyof T] } }时,它显示tableDataFormatter始终为value

用法:

string | number

所以我必须抑制错误 因为该功能按预期工作,所以我明确将public formatData<IBenefit> (data: ReadonlyArray<IBenefit>): ReadonlyArray<ITableData<IBenefit>> { return super.formatData(data).map((d: ITableData<IBenefit>) => ({ ...d, stores: { ...d.stores, component: <Addon addonValues={d.stores.value} /> // d.stores.value should be an Array but it's being shown as ReactText/string } })) }分配为value

1 个答案:

答案 0 :(得分:1)

您的ITableData<T>接口无效的TypeScript。具体来说,您正在尝试使用约束为keyof T的{​​{3}},但是唯一允许的索引签名类型是stringnumber。相反,您应该考虑使用index signature而不是接口。它将为您提供所需的映射:

type ITableData<T> = {
  readonly [K in keyof T]: {
    readonly component: React.ReactNode
    readonly value: T[K]
  }
}

请注意嵌套的value属性是T[K]类型而不是T[keyof T]类型。 T[keyof T]将成为T所有值类型的并集,并且从每个键到每个值的映射都将丢失。但是T[K]意味着对于每个键K,嵌套的value属性与由T索引的K的原始属性具有相同的类型。这是避免string | number问题的方法。

然后针对tableDataFormatter(),我将更改一些注释和断言,如下所示:

// strip off the readonly modifier for the top level properties
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

// explicitly declare that the function returns ITableData<T>
export function tableDataFormatter<T extends Record<keyof T, React.ReactNode>>(
  d: T
): ITableData<T> {

  // assert that the return value will be ITableData<T> but make it
  // mutable so we can assign to it in the function without error
  const formatedData = {} as Mutable<ITableData<T>>;

  // assert that Object.keys(d) returns an array of keyof T types
  // this is not generally safe but is the same as your "as keyof T"
  // assertions and only needs to be done once.
  (Object.keys(d) as Array<keyof T>).forEach(key => {
    formatedData[key] = {
      value: d[key],
      component: d[key]
    }
  })

  return formatedData
}

希望它能按您现在期望的方式工作。祝你好运!