Within my code, I have a state
, interface
, and a function
that handles API data processing.
const [series, setSeries] = useState<ISeries[]>([])
export interface ITicket {
status?: string
status_desc?: string
keyword_language?: string
}
interface ISeries {
colorByPoint: boolean
data: {
name: string
y: number
status: string | undefined
keyword_language: string | undefined
}[]
}
The function responsible for processing the API data is defined as follows:
function trans(series: ITicket[]) {
const data = series.map(s => {
return {
**//api only reuturn either s.status_desc or s.keyword_language, only one**
name: s.status_desc ? s.status_desc : s.keyword_language,
y: s.ticket_count,
status: s?.status,
keyword_language: s?.keyword_language,
}
})
return [
{
colorByPoint: true,
data,
},
]
}
While setting the name
property in the function for processing the API data, an error occurs due to TypeScript expecting the value to be a string, but with a chance of it being undefined
.
Question:
It is certain that the API will provide either s.status_desc
or s.keyword_language
as a string
. How can this error be resolved without altering the type for name
or using TypeScript ignore (@ts-ignore
)?
Keep in mind that changing the type in the interface for status_desc
and keyword_language
is not possible, as the API could potentially send only one of them. Therefore, the types must remain as undefined
in both cases.