uni-app Type mismatch: inferred type is String but Number was expected

发布于 1周前 作者 itying888 来自 Uni-App

uni-app Type mismatch: inferred type is String but Number was expected

示例代码:

let uuid: String[] = new Array(10).fill("");

操作步骤:

let uuid: String[] = new Array(10).fill("");

预期结果:

声明一个长度为 10 的字符串数组


## 实际结果:

 fill 中,非要我传递一个 number 

bug描述:

双引号地方 报 Type mismatch: inferred type is String but Number was expected‌


1 回复

The error message “Type mismatch: inferred type is String but Number was expected” indicates that your code is trying to use a String where a Number is required. This is a common issue in TypeScript or JavaScript when dealing with type mismatches.

Here’s how you can resolve this issue in a uni-app project:

1. Explicitly Convert the String to a Number

If you have a string that represents a number and you need to use it as a number, you can convert it using one of the following methods:

  • Number(): Converts a string to a number.

    let str = "123";
    let num = Number(str); // num is now a number
  • parseInt(): Parses a string and returns an integer.

    let str = "123";
    let num = parseInt(str, 10); // num is now a number
  • parseFloat(): Parses a string and returns a floating-point number.

    let str = "123.45";
    let num = parseFloat(str); // num is now a number

2. Check the Source of the String

If the string is coming from user input, an API, or another source, ensure that it is properly validated and converted before using it in a context that expects a number.

3. TypeScript Type Annotations

If you’re using TypeScript, you can use type annotations to ensure that the correct type is used:

let str: string = "123";
let num: number = Number(str); // Explicitly convert to number

4. Example in uni-app

Here’s an example of how you might encounter and resolve this issue in a uni-app component:

<template>
  <view>
    <input v-model="inputValue" type="text" placeholder="Enter a number" />
    <button @click="calculate">Calculate</button>
  </view>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';

export default defineComponent({
  setup() {
    const inputValue = ref('');

    const calculate = () => {
      // Convert the string input to a number
      const num = Number(inputValue.value);

      if (isNaN(num)) {
        console.error('Invalid number');
        return;
      }

      // Now you can use `num` as a number
      console.log('Number:', num);
    };

    return {
      inputValue,
      calculate,
    };
  },
});
</script>

5. Debugging Tips

  • Check the Type: Use typeof to check the type of the variable.
    console.log(typeof str); // Should be "string"
    console.log(typeof num); // Should be "number"
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!