Skip to content

Commit

Permalink
Infer optional / promise args type correctly (#2740)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel K <[email protected]>
  • Loading branch information
iChenLei and FredyC authored Jan 23, 2021
1 parent 695108c commit 83b84fd
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/calm-files-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mobx": patch
---

Infer optional / promise `action` args type correctly
47 changes: 34 additions & 13 deletions packages/mobx/__tests__/v5/base/typescript-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2086,19 +2086,40 @@ test("type inference of the action callback", () => {
)

// Promises
// TODO: re-enable
// Promise.resolve(1).then(
// action(arg => {
// assert<IsExact<typeof arg, number>>(true)
// })
// )

// // Promises with names actions
// Promise.resolve(1).then(
// action("named action", arg => {
// assert<IsExact<typeof arg, number>>(true)
// })
// )
Promise.resolve(1).then(
action(arg => {
assert<IsExact<typeof arg, number>>(true)
})
)

// Promises with names actions
Promise.resolve(1).then(
action("named action", arg => {
assert<IsExact<typeof arg, number>>(true)
})
)

// optional
const optionalActionTypeInfer: {
a?: (a1: number, a2: string, a3: boolean) => void
} = {
a: action((a1, a2, a3) => {
assert<IsExact<typeof a1, number>>(true)
assert<IsExact<typeof a2, string>>(true)
assert<IsExact<typeof a3, boolean>>(true)
})
}

// optional with names actions
const optionalNamedActionTypeInfer: {
a?: (a1: number, a2: string, a3: boolean) => void
} = {
a: action("named action", (a1, a2, a3) => {
assert<IsExact<typeof a1, number>>(true)
assert<IsExact<typeof a2, string>>(true)
assert<IsExact<typeof a3, boolean>>(true)
})
}
})

test("TS - it should support flow as function wrapper", done => {
Expand Down
4 changes: 2 additions & 2 deletions packages/mobx/src/api/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ const ACTION_UNNAMED = "<unnamed action>"

export interface IActionFactory extends Annotation, PropertyDecorator {
// nameless actions
<T extends Function>(fn: T): T
<T extends Function | undefined | null>(fn: T): T
// named actions
<T extends Function>(name: string, fn: T): T
<T extends Function | undefined | null>(name: string, fn: T): T

// named decorator
(customName: string): PropertyDecorator & Annotation
Expand Down

0 comments on commit 83b84fd

Please sign in to comment.