microsoft / microsoft/TypeScript
Treating `undefined` parameters as optional
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
tsc: 2.2.0-dev.20161116
Discover this behavior from https://github.com/acdlite/flux-standard-action/pull/45/commits/78a9065914b2ca4848dfba8fc0b47c54e2d0e319
This is the original code:
export interface FSA<Payload, Meta> {
...
payload?: Payload;
...
}
However, this does not work well with type guard:
function isSomeAction(action: any): action is FSA<{ message: string }, void> {
return true;
}
let action = {...};
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:
export interface FSA<Payload, Meta> {
...
payload: Payload;
...
}
// now type guard works
let action = {...};
if (isSomeAction(action)) {
console.log(action.payload.message);
}
However, now the creation code fail:
function createSomeAction(): FSA<undefined, undefined> {
// error: `payload` and `meta` are required
return { type: 'SOME_ACTION' };
}
The workaround is to depends on infer type:
function createSomeAction() {
return { type: 'SOME_ACTION' };
}
or specify it:
function createSomeAction(): FSA<undefined, undefined> {
return {
type: 'SOME_ACTION',
payload: undefined,
meta: undefined
};
}
Is there a better solution? 🌷
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the FSA<Payload, Meta> interface examples and the type-guard and createSomeAction snippets in the issue. Compare the behavior when payload and meta are optional with the behavior when they are required, and determine what outcome should preserve both narrowing and creation of undefined-valued actions.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100