itsource

반응 유형 스크립트 - 유형의 인수를 유형의 매개 변수에 할당할 수 없습니다.

mycopycode 2023. 3. 23. 22:44
반응형

반응 유형 스크립트 - 유형의 인수를 유형의 매개 변수에 할당할 수 없습니다.

데모가 있습니다.

Typescript와 훅을 사용하여 아래와 같이 간단한 형태로 엔트리를 캡처하는 리액트 앱입니다.

여기 Stackblitz에서는 동작합니다만, 로컬에서는 VS 코드를 사용하고 있기 때문에, 에러가 발생합니다.setUser(userData);에러는

const userData: {
    username: string;
    password: string;
    prevState: null;
}
Argument of type '{ username: string; password: string; prevState: null; }' is not assignable to parameter of type '(prevState: null) => null'.
  Type '{ username: string; password: string; prevState: null; }' provides no match for the signature '(prevState: null): null'.ts(2345)

이 타이프 스크립트 오류를 방지하려면 어떻게 해야 합니까?

const [user, setUser] = useState(null);

이것은 활자를 부여하지 않았기 때문에, 활자 원고가 추론해 보아야 합니다.null로 통과된 것을 인식하기 때문에 이 상태는 null로 간주됩니다(그리고 항상 null로 간주됩니다).대신 다음과 같이 유형을 지정해야 합니다.

interface UserData {
  username: string;
  password: string;
  prevState: null
}

//...
const [user, setUser] = useState<UserData | null>(null);

API에서 데이터를 가져오려면 다음이 필요합니다.

import React, { useState, useEffect } from 'react'
import axios from 'axios';

const MyComponent = () => {
const [data, setData] = useState<any | null>(null);
const fetchData = () => {
(...) //Axios.get() or async if u await data.
setData(fetchData)
}
}
useEffect(() =>{
    fetchData()
}, [])

언급URL : https://stackoverflow.com/questions/59125973/react-typescript-argument-of-type-is-not-assignable-to-parameter-of-type

반응형