Skip to content

Commit

Permalink
🏷️ Improve type inference
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jul 2, 2021
1 parent 9e3a626 commit 792ab61
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
29 changes: 24 additions & 5 deletions common/last.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,25 @@
import { isArray } from '../deps.ts'
import { ifElse } from '../src/ifElse.ts'
import { takeLast } from '../src/takeLast.ts'
import { String2Array } from '../src/types/index.ts'

/**
* @example
* ```ts
* LastString<''> // ''
* LastString<'a'> // 'a'
* LastString<'abcdefghijk'> // 'k'
* ```
*
* @internal
*/
type LastString<T extends string> = T extends `${infer L}${infer R}`
? R extends ''
? L
: LastString<R>
: T extends ''
? ''
: string

/**
* Infer the last types.
*
Expand Down Expand Up @@ -30,10 +48,8 @@ import { String2Array } from '../src/types/index.ts'
*
* @public
*/
type Last<T extends string | readonly unknown[]> = T extends ''
? ''
: T extends string
? [never, ...String2Array<T>][String2Array<T>['length']]
type Last<T extends string | readonly unknown[]> = T extends string
? LastString<T>
: T extends never[] | []
? undefined
: T extends readonly [...infer _, infer L]
Expand All @@ -46,6 +62,9 @@ type Last<T extends string | readonly unknown[]> = T extends ''
* @param val - `string` or any `array` object
* @returns The last element of the `val`
*
* @remarks
* The maximum number of characters for the type system to work properly is 24.
*
* @example
* ```ts
* // String
Expand Down
1 change: 1 addition & 0 deletions common/last_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,5 @@ Deno.test('Last', () => {
assertEqual<string, Last<string>>()
assertEqual<'', Last<''>>()
assertEqual<'o', Last<'hello'>>()
assertEqual<'x', Last<'abcdefghijklmnopqrstuvwx'>>()
})

0 comments on commit 792ab61

Please sign in to comment.