打字稿使用字符串或字符串[]

时间:2021-01-28 15:32:47

标签: reactjs string typescript

我有这个定义:

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

但是如果我这样做,我的文本编辑器就会出错:

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

它说 string[] 没有实现修剪。我的方法错了吗?我应该使用2个接口吗?谢谢

更新:

我的 tsconfig.json:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "jsx": "react-native",
    "lib": ["dom", "esnext"],
    "moduleResolution": "node",
    "noEmit": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "strict": true,
    "baseUrl": ".",
    "paths": {
      "*": ["*", "src/*"]
    }
  }
}

1 个答案:

答案 0 :(得分:3)

出现此错误是因为您使用了一个变量:i 来遍历您的对象。

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
}

在两行之间:

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

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

TypeScript 认为 answerArray[i] 可能会导致不同的值。


解决办法是将值存储在指针中,例如:

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
}