此表达式不可调用。类型“ {}”没有呼叫签名。 TS2349

时间:2020-07-16 10:33:56

标签: reactjs typescript react-hooks

# Generated by Django 3.0.6 on 2020-07-16 10:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trading', '0011_auto_20200714_0758'), ] operations = [ migrations.AddField( model_name='account', name='instrument', field=models.CharField(blank=True, choices=[('future', 'future'), ('swap', 'swap')], max_length=12, null=True), ), migrations.AlterField( model_name='account', name='trading', field=models.BooleanField(default=True), ), ] 的一个非常常见的TypeScript错误TS2349。

在不同情况下,它可以通过不同的解决方法来解决。但是,在处理React的上下文时,我发现的最佳解决方案是使用sth has no call signatures

在这种情况下,正确的方法是什么?

// @ts-ignore
// auth.tsx

import { CurrentUserContext } from 'components/currentUser';
import React, { useState, useEffect, useContext } from 'react';

const Auth = ({ onLogin }: {onLogin: any}) => {

  const [, setCurrentUserState] = useContext(CurrentUserContext);
  const [credentials, { data }] = useMutation(AUTH);

  ...

  useEffect(() => {
    if (data) {

      // TypeScript Error without @ts-ignore:
      // This expression is not callable.
      // Type '{}' has no call signatures.  TS2349

      // @ts-ignore
      setCurrentUserState((state: any) => ({
        ...state,
        currentUser: data.login.author,
      }))
    }
  }, [data, setCurrentUserState]);

  return <div>{data.login.author}</div>
}

n.b。 “反应”:“ ^ 16.13.1” “ typescript”:“〜3.7.2”

1 个答案:

答案 0 :(得分:3)

描述并明确指定类型:

type IUserState = {
    currentUser?: object;
};

type ICurrentUserContext = [IUserState, React.Dispatch<React.SetStateAction<IUserState>>];

const CurrentUserContext = React.createContext<ICurrentUserContext>([{}, () => null]);

const CurrentUserProvider = ({ children }: { children: any }) => {
    const [state, setState] = useState<IUserState>({
        currentUser: null,
    });

    return <CurrentUserContext.Provider value={[state, setState]}>{children}</CurrentUserContext.Provider>;
};