typescript - 对象的 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
})
解决方案
推荐阅读
- java - 我需要对两个从单独的 SQL 查询返回的 livedata 对象执行算术运算(减法)
- javascript - React Navigation 5 参数传递的问题
- ruby-on-rails - 隐藏字段值被误解
- python - @bot.message_handler() 中的 lamda 函数在 Telebot python 中无法正常工作
- regex - 使用动态前瞻获取字符串的一部分
- angularjs - ANGULAR JS:向一个 Angular 模块添加多个工厂和指令
- android - HiltWorkerFactory:在 AppStartup 中配置 WorkManagerInitializer
- python - Telethon:对 Telegram 的自动回复停止工作。怎么修?
- opencl - 如何在矢量处理器 SIMD 上的 opencl 中添加矢量(int16)的所有元素?
- c# - 如何使用 System.IO.Pipelines 包创建响应 TCP 侦听器?