声明类型既不是“ void”也不是“ any”的函数必须返回一个值。 TypeScript / React

时间:2019-09-08 20:07:09

标签: javascript reactjs typescript

在我的组件中,我有一个名为AuthForm的函数,该函数使用开关来呈现3个组件中的1个。在方法参数中,我传入了一组类方法。除了如何正确键入类方法本身之外,我已经了解了所有类型。

错误:

  

(别名)接口ISignInData

     

导入ISignInData

     

声明类型既不是'void'也不是'any'的函数必须返回值。ts(2355)

enter image description here

首先是接口和类型

export interface ISignInData {
  email: string
  password: string
}

export interface IAccountData {
  email: string
  password: string
  password2: string
}

export interface IForgotData {
  email: string
}

export type TSignIn = (email: string, password: string) => (ISignInData)

export type TCreateAccount = (email: string, password: string, password2: string) => (IAccountData)

export type TForgot = (email: string) => (IForgotData)

组件

import React from 'react'

import { Astronaut, Login, Create, Forgot, NomicsLink } from '../components'
import { TSignIn, TCreateAccount, TForgot, ISignInData, IAccountData, IForgotData } from '../shared/types'
import { AuthContainer } from '../styles'

interface IState { view: string }

interface IAuthView {
  type: string
  methods: [
    (email: string, password: string) => ISignInData,
    (email: string, password: string, password2: string) => IAccountData,
    (email: string) => IForgotData
  ]
  changeView: any
}

const AuthForm = ({ type, methods, changeView }: IAuthView) => {
  switch(type) {
    case 'signin':
      return <Login signIn={methods[0]} changeView={changeView} />
    case 'create':
      return <Create createAccount={methods[1]} changeView={changeView} />
    case 'forgot':
      return  <Forgot resetPassword={methods[2]} changeView={changeView} />
    default:
      return null;
  }
}

class Account extends React.Component<null, IState> {
  constructor(props: any) {
    super(props);
    this.state = { view: 'signin' }
  }

  render() {
    const { view } = this.state;

    return (
      <div id="login-container">
        <AuthContainer>
          {
            <AuthForm
              type={view}
              methods={[this.handleSignIn, this.handleCreateAccount, this.handleResetPassword]}
              changeView={this.handleChangeView}
            />
          }
        </AuthContainer>
        <NomicsLink />
        <Astronaut className="astronaut" showLogo={false}/>
      </div>
    )
  }

  handleSignIn = (email: string, password: string): ISignInData => {
    console.log('handleSignIn')
  }

  handleCreateAccount = (email: string, password: string, password2: string): IAccountData => {
    console.log('handleSignIn')
  }

  handleResetPassword = (email: string): IForgotData => {
    console.log('handleResetPassword')
  }

  handleChangeView = (view: string) => {
    console.log('handleChangeView')
    this.setState({ view })
  }
}

export default Account

1 个答案:

答案 0 :(得分:2)

您已将ISignInData声明为返回类型。但是该方法不返回任何内容。如果您不打算返回任何内容,只需将其更改为void

handleSignIn = (email: string, password: string): void => {
    console.log('handleSignIn')
}