tradingview / lightweight-charts

Performant financial charts built with HTML5 canvas
https://www.tradingview.com/lightweight-charts/
Apache License 2.0
9.47k stars 1.63k forks source link

[Typescript] WhitespaceData value typescript error #1699

Open yoyo201626 opened 1 month ago

yoyo201626 commented 1 month ago

Lightweight Charts™ Version: ^4.2.0 Steps/code to reproduce: env: vite vue3 ts Lightweight Charts

const chart = createChart('container', chartOptions)

chart.timeScale().applyOptions(timeScaleOptions)

const areaSeries = chart.addAreaSeries()
areaSeries.applyOptions(areaSeriesOptions)

areaSeries.setData([
    { time: '2018-12-12', value: 24.11 },
    { time: '2018-12-13', value: 31.74 },
])
const lastIndex = areaSeries.data().length - 1
const lastestData = areaSeries.dataByIndex(lastIndex)
if(lastestData) {
    const lastestValue = lastestData.value
}

Actual behavior:

Property 'value' does not exist on type 'AreaData<Time> | WhitespaceData<Time>'.
  Property 'value' does not exist on type 'WhitespaceData<Time>'.ts(2339)
any

Expected behavior:

I can get lastestData.value without typescript error

Screenshots:

image CodeSandbox/JSFiddle/etc link:

https://codesandbox.io/p/devbox/immutable-sky-jvgvx4?file=%2Fsrc%2Ftest.ts%3A43%2C1

import { createChart } from "lightweight-charts"

const chartOptions = { 
    autoSize: true,
    localization: {
        locale: 'en-US',
    },
    kineticScroll: {
        touch: true,
        mouse: true
    }
}

const areaSeriesOptions = {
    lineColor: '#ffb018',
    topColor: 'rgba(255, 176, 24, 0.3)',
    bottomColor: 'rgba(255, 176, 24, 0)',
}

const timeScaleOptions = {
    timeVisible: true,
    minBarSpacing: 0,
    barSpacing: 10,
}

const chart = createChart('container', chartOptions)

chart.timeScale().applyOptions(timeScaleOptions)

const areaSeries = chart.addAreaSeries()
areaSeries.applyOptions(areaSeriesOptions)

areaSeries.setData([
    { time: '2018-12-12', value: 24.11 },
    { time: '2018-12-13', value: 31.74 },
])
const lastIndex = areaSeries.data().length - 1
const lastestData = areaSeries.dataByIndex(lastIndex)
if(lastestData) {
    const lastestValue = lastestData.value
}
yoyo201626 commented 1 month ago

it may resolve by const lastestData = areaSeries.dataByIndex(lastIndex) as AreaData<Time>, but can we solve this more gracefully?