Skip to content

Treating undefined parameters as optional #12400

Description

@unional

tsc: 2.2.0-dev.20161116

Discover this behavior from redux-utilities/flux-standard-action@78a9065

This is the original code:

exportinterfaceFSA<Payload,Meta>{
...
payload?: Payload;
...
}

However, this does not work well with type guard:

functionisSomeAction(action: any): action is FSA<{message: string},void>{returntrue;}letaction={...};if(isSomeAction(action)){// `action.payload` may be undefined.console.log(action.payload.message);}

Since generic type can be anything, including undefined, I'm considering to remove the optional designation:

exportinterfaceFSA<Payload,Meta>{
...
payload: Payload;
...
}// now type guard worksletaction={...};if(isSomeAction(action)){console.log(action.payload.message);}

However, now the creation code fail:

functioncreateSomeAction(): FSA<undefined,undefined>{// error: `payload` and `meta` are requiredreturn{type: 'SOME_ACTION'};}

The workaround is to depends on infer type:

functioncreateSomeAction(){return{type: 'SOME_ACTION'};}

or specify it:

functioncreateSomeAction(): FSA<undefined,undefined>{return{type: 'SOME_ACTION',payload: undefined,meta: undefined};}

Is there a better solution? 🌷

Metadata

Metadata

Assignees

No one assigned

    Labels

    CommittedThe team has roadmapped this issueHelp WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions