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
125 views
in Technique[技术] by (71.8m points)

reactjs - Typescript use string or string[]

I have this definition:

interface Field {
  question: string,
  answer: string | string[],
}

but theres error in my text editor if i do this:

if (typeof answer === 'string') {
  const notEmpty = answer.trim().length > 0
}

it says string[] doesn't implement trim. is my approach wrong? should i use 2 interfaces? thanks

updated:

my tsconfig.json:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "jsx": "react-native",
    "lib": ["dom", "esnext"],
    "moduleResolution": "node",
    "noEmit": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "strict": true,
    "baseUrl": ".",
    "paths": {
      "*": ["*", "src/*"]
    }
  }
}
question from:https://stackoverflow.com/questions/65940265/typescript-use-string-or-string

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

1 Answer

0 votes
by (71.8m points)

You have this error because you use a variable : i to go throught your object.

playground

interface Field {
  question: string,
  answer: string | string[],
}

const answerArray: Field['answer'][] = ['tes'];

const i = 0;

if (typeof answerArray[i] === 'string') {
  const notEmpty = answerArray[i].trim().length > 0
}

Between the two line :

if (typeof answerArray[i] === 'string') {

const notEmpty = answerArray[i].trim().length > 0

TypeScript consider that answerArray[i] could result in different values.


The soluce is to store the value inside of a pointer, like :

playground

interface Field {
  question: string,
  answer: string | string[],
}

const answerArray: Field['answer'][] = ['tes'];

const i = 0;

const myAnswer = answerArray[i];

if (typeof myAnswer === 'string') {
  const notEmpty = myAnswer.trim().length > 0
}

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

...