首页 > 解决方案 > 对象的 TypeScript 类型,指定了一个属性类型,而所有其他属性类型都是不同的类型

问题描述

我需要一个图形数据的通用类型,它总是包含endDate: Date所有其他属性必须是number. 这不起作用:

type GraphDatumEndDateType = { endDate: Date }
type GraphDatumType = Record<string, number> & GraphDatumEndDateType

它抛出:

      Property 'endDate' is incompatible with index signature.
        Type 'Date' is not assignable to type 'number'.ts(2322)

当一个函数GraphDataType作为参数被调用时:

export function getGraphData<T extends GraphDatumType>({
  data
}: {
  data: T[]
}): T[] {
  return data
}

const data = [
  {
    a: 0.8,
    b: 0.2,
    endDate: new Date
  }
]

const result = getGraphData({
  data // ts errors here
})

标签: typescript

解决方案


推荐阅读