Skip to content

Commit

Permalink
feat: add assertType.hasProperty() (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
unional committed Jan 5, 2020
1 parent e1afb93 commit 89e2dbb
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -100,6 +100,7 @@ assertType.isFalse(assignability<YourType>()(subject))
- `assertType<T>(subject)`: assert `subject` satisfies type `T`.
- `assertType.isXXX(value)`: ensure typeof `value` is `XXX`
- `assertType.noXXX(value)`: ensure typeof `value` does not contain `XXX`. i.e. cannot assign `XXX` to `value`.
- `assertType.hasProperty(value, prop)`: assert `value` has property `prop`. This will pick the correct union type.
- `typeAssert.*` (deprecated) replaced by `assertType`.
- `typeAssertion<T>()`: creates a type assertion function of type `T`

Expand Down
15 changes: 15 additions & 0 deletions src/assertType.spec.ts
Expand Up @@ -168,3 +168,18 @@ describe('noString()', () => {
// typeAssert.noString('a' as string | undefined)
})
})

describe('hasProperty', () => {
type X = { name: string } & ({ a: 1 } | { b: 2 })

const x: X = { name: 'n', a: 1 } as any

assertType.hasProperty(x, 'a')

expect(x.a).toBe(1)

const y: X = { name: 'n', b: 2 } as any
assertType.hasProperty(y, 'b')

expect(y.b).toBe(2)
});
6 changes: 6 additions & 0 deletions src/assertType.ts
@@ -1,3 +1,5 @@
import { UnionKeys } from './UnionKeys'

/**
* assert the subject satisfies the specified type T
* @type T the type to check against.
Expand All @@ -17,6 +19,10 @@ assertType.isFalse = noop as (value: false) => void
assertType.isString = noop as (value: string) => void
assertType.noString = noop as <T>(value: Exclude<T, string>) => void
assertType.isNever = noop as (value: never) => void

// eslint-disable-next-line @typescript-eslint/no-unused-vars
assertType.hasProperty = function hasProperty<T, P extends UnionKeys<T>>(value: T, prop: P): asserts value is T & Record<P, T[P]> { }

// assertType.hasProperty = <T>(value: T, propertyName: KeyTypes)
function noop() { return }

Expand Down

0 comments on commit 89e2dbb

Please sign in to comment.