Home > Enterprise >  How to let typescript know the variable must be a string, but not undefine without faking?
How to let typescript know the variable must be a string, but not undefine without faking?

Time:07-12

I have a state, interface , and a function that process the API data

  • 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
  }[]
}

function that process the api Data

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,
    },
  ]
}

In the function that process the API data, I am checking what value was passed in order to set the name property.

    return {
**//api only reuturn either s.status_desc or s.keyword_language, only one** 
      name: s.status_desc ? s.status_desc : s.keyword_language, 

But then I get a TypeScript compilor error that it is not assignable since name must be a string. Now there is chance that it can be undefined.

Question:

I am sure that API will pass either s.status_desc or s.keyword_language as a string. So name will get a string value to assign.

I dont want to change the type for name to string | undefined

I don't want to use TypeScript ignore (@ts-ignore) to by pass the error.

How can I get rid of the error without faking?

bear in mind: in the interface, I cant change the type of status_desc and keyword_language in order to bypass it because API could either pass me one. So I have to keep the type as undefined for both cases

CodePudding user response:

Simplest way: name: s.status_desc || s.keyword_language || ""

console.log(null || undefined || "" || "asd" || ""); will print "asd"

return {
    name: s.status_desc || s.keyword_language || "",
    y: s.ticket_count,    
    status: s.status,
    keyword_language: s?.keyword_language,
}

So if by any chance both fields are null or undefined - your code will not fail with error trying to access null field name (it will be an empty string)

Or you can use Non-Null Assertion Operator !:

Considered as a bad practice but can help anyway.

name: s.status_desc! || s.keyword_language!

CodePudding user response:

I would suggest to just cast the variable and add a comment like so:

{
  // Cast because server will always serv a string for at least one of the two
  name: (s.status_desc || s.keyword_language) as string,
}
  • Related