2

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/*"]
    }
  }
}
14
  • const notEmpty = (answer as string).trim().length > 0 Commented Jan 28, 2021 at 15:35
  • 2
    I can't reproduce Commented Jan 28, 2021 at 15:38
  • 3
    I cannot reproduce your error. Please provide a minimal reproducible example which actually demonstrates your issue. Commented Jan 28, 2021 at 15:39
  • 2
    @Gh05d except that per my and jcalz's comments, it doesn't complain... Commented Jan 28, 2021 at 15:40
  • 1
    It's probably that i is of type number and the compiler doesn't know how to narrow based on that. Without a minimal reproducible example though I'm not going to go through the effort of demonstrating this. If you want to increase your chances of getting a helpful response, I suggest you follow the guidelines in How to Ask, specifically about providing a minimal reproducible example suitable for dropping into a standalone IDE. Good luck! Commented Jan 28, 2021 at 15:51

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

thank you so much,,, how is this possible ?!
Where did this code come from? That's not in the question...
@Aron I did retro engineered it based on the code provided by OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.