如何预防"预期1个参数,但得到0"当预期的参数是“未定义”时?

时间:2017-12-18 03:28:38

标签: 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.

我能做些什么来修复&#34;预期的1个参数,但得到0&#34;问题?我通过将undefined指定为默认值来设置TypedAction奇怪吗?

1 个答案:

答案 0 :(得分:0)

使用void而不是未定义的