Skip to content

Commit

Permalink
feat: add unknown to Narrow (#187)
Browse files Browse the repository at this point in the history
  • Loading branch information
tmm committed Aug 18, 2023
1 parent 54a8985 commit 4a0131f
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/nice-shirts-punch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"abitype": patch
---

Added `unknown` support to `Narrow`
3 changes: 0 additions & 3 deletions rome.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@
"enabled": true,
"rules": {
"recommended": true,
"complexity": {
"noExtraSemicolon": "off"
},
"correctness": {
"noUnusedVariables": "error"
},
Expand Down
7 changes: 4 additions & 3 deletions src/narrow.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { assertType, test } from 'vitest'
import { assertType, expectTypeOf, test } from 'vitest'

import type { Narrow } from './narrow.js'
import { narrow } from './narrow.js'

test('Narrow', () => {
assertType<Narrow<['foo', 'bar', 1]>>(['foo', 'bar', 1])
expectTypeOf<Narrow<['foo', 'bar', 1]>>().toEqualTypeOf<['foo', 'bar', 1]>()
expectTypeOf<Narrow<unknown>>().toEqualTypeOf<unknown>()
})

test('narrow', () => {
const asConst = narrow(['foo', 'bar', 1])
// ^?
type Result = typeof asConst
assertType<Result>(['foo', 'bar', 1])
expectTypeOf<Result>().toEqualTypeOf<['foo', 'bar', 1]>()

assertType<'foo'>(narrow('foo'))
assertType<1>(narrow(1))
Expand Down
7 changes: 3 additions & 4 deletions src/narrow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@
*/
// s/o https://twitter.com/hd_nvim/status/1578567206190780417
export type Narrow<TType> =
| (unknown extends TType ? unknown : never)
| (TType extends Function ? TType : never)
| (TType extends string | number | boolean | bigint ? TType : never)
| (TType extends bigint | boolean | number | string ? TType : never)
| (TType extends [] ? [] : never)
| {
[K in keyof TType]: Narrow<TType[K]>
}
| { [K in keyof TType]: Narrow<TType[K]> }

/**
* Infers embedded primitive type of any type
Expand Down

1 comment on commit 4a0131f

@vercel
Copy link

@vercel vercel bot commented on 4a0131f Aug 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

abitype – ./

abitype-wagmi-dev.vercel.app
abitype.vercel.app
abitype-git-main-wagmi-dev.vercel.app
abitype.dev

Please sign in to comment.