【问题标题】:How to prevent "Expected 1 arguments, but got 0" when the expected argument is `undefined`?当预期参数为“未定义”时,如何防止“预期 1 个参数,但得到 0”?
【发布时间】:2020-07-07 23:17:00
【问题描述】:

Typescript 版本:2.6.2

我正在尝试使 redux 比使用开箱即用的 typedef 获得的类型更安全,同时还减少了一些样板文件。我认为我真的接近我正在寻找的东西 - 除了一个例外。这是我得到的:

// Action definiton from redux typedefs
interface Action {
  type: any;
}

// Action type using generics
// T is intended to be a string literal
// P is optional, so it defaults to undefined
interface TypedAction<T extends string, P = undefined> extends Action {
    readonly type: T;
    readonly payload: P;
}

// Function for generating the most common type of action creator
// Takes a TypedAction as its generic arg and uses that to infer
// what is required as the payload in the returned action creator
function makeActionCreator<T extends TypedAction<any, any>>(
    type: T['type'],
): (p: T['payload']) => T {
    return payload => ({ type, payload } as T);
}

//=================
// Example usage //
//=================

interface EmailPasswordCredential {
    readonly email: string;
    readonly password: string;
}

enum SignUpActionType {
    executeSignUp = 'SignUp/executeSignUp',
    reportSuccess = 'SignUp/reportSuccess',
    reportError = 'SignUp/reportError',
}

////
// Action Types
////

// Sign-up action
// requires an email and password to be specified
type ExecuteSignUpAction = TypedAction<
    SignUpActionType.executeSignUp,
    EmailPasswordCredential
>;

// Success action
// Doesn't need a payload
type ReportSignUpSuccessAction = TypedAction<SignUpActionType.reportSuccess>;

// Error action
// Fired when something didn't work (like a 400)
// Error is passed back as the payload
type ReportSignUpErrorAction = TypedAction<SignUpActionType.reportError, Error>;

////
// Action Creators
////

const signUp = makeActionCreator<ExecuteSignUpAction>(
    SignUpActionType.executeSignUp,
);

const reportSignUpSuccess = makeActionCreator<ReportSignUpSuccessAction>(
    SignUpActionType.reportSuccess,
);

const reportSignUpError = makeActionCreator<ReportSignUpErrorAction>(
    SignUpActionType.reportSuccess, // because of the generic - this correctly errors from the type mismatch
);

// the real problem:

// this correctly errors, an EmailPasswordCredential is required
signUp(); 

// this, however, should be allowed. 
//the missing argument is "undefined", which is what we are passing, by passing nothing.
reportSignUpSuccess();

// this fixes the type error, but feels unnecessary
reportSignUpSuccess(undefined);

You can see the full example with syntax highlighting and inline errors here.

我可以做些什么来解决“预期 1 个参数,但得到 0”的问题吗?我是否通过将 undefined 指定为默认值来设置 TypedAction 很奇怪?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    使用void 而不是未定义。

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 1970-01-01
      • 2022-01-24
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2021-08-22
      • 2019-08-28
      相关资源
      最近更新 更多