首页 > 解决方案 > 类型 'boolean' 不可分配给类型 'number'.ts

问题描述

这是我的代码

App.tsx

import React, { useState } from 'react';
import logo from './logo.svg';
import './App.css';
import { TextField } from './components/TextField';

function App() {

  return (
    <div className="App">
      <TextField name='fef' age=12/>
    </div>
  );
}

export default App;

TextField.tsx

import React,{useEffect, useRef, useState} from "react";

interface Props{
    name: string;
    age: number;
}

export const TextField:React.FC<Props> = ({name,age}) => {
    return (
        <div>
            <h2>Hello {name}, and I know that you are {age} years old</h2>
        </div>
    );
}

但是我收到了这个错误!

Type 'boolean' is not assignable to type 'number'.ts(2322)
TextField.tsx(5, 5): The expected type comes from property 'age' which is declared here on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

在此处输入图像描述


我应该怎么做?

请给我一个解决方案。我是 React 和 Typescript 的新手。

标签: reactjstypescript

解决方案


数字作为道具应该在大括号内传递。只有字符串可以在没有大括号的情况下传递,但它们必须包含在引号内,就像你的name道具一样。

  return (
    <div className="App">
      <TextField name='fef' age={12}/>
    </div>
  );

推荐阅读