Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

typescript - How to push to something typed `string | string[]`

I struggle with a field typed string | string[].

I assign an array to it but if I want to push a string to it i get a type error.

For illustration see this fragment:

  let col: AgGridColumnProps = {
    ...
    type: [field.type.toLowerCase()]
  }

  for (const [ending, tmp] of Object.entries(nameEndingMap)) {
    if (theName.endsWith(ending)) {
      const typ: string = tmp[0]
      ...
      col.type.push(typ)
    }
  }

Results in this error:

Property 'push' does not exist on type 'string | string[]'.
  Property 'push' does not exist on type 'string'.

The definition of type from Ag-Grid is type?: string | string[].

How can I make typescript understand, that pushing to type is valid here?

Edit: While

  let col: AgGridColumnProps = {
    cellClass: type2classMap[field.type.toLowerCase()],
    type: [field.type.toLowerCase()]

  }

does not compile due to thye error mentioned above,

  let col: AgGridColumnProps = {}
  col.cellClass = type2classMap[field.type.toLowerCase()]
  col.type = [field.type.toLowerCase()]

compiles fine. I'm still dumbfolded what is happening there. I also was unable to reproduce this issue on a minimal example as suggested by Mike S.

question from:https://stackoverflow.com/questions/65882747/how-to-push-to-something-typed-string-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have a union type, you will need to assert the type before using a type specific method/property;

So instead of:

strarr.push(item);

you write:

(strarr as string[]).push(item);

or (type safe):

if(Array.isArray(strarr)) strarr.push(item);

Example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...