feat(typescript-types): Add KeyPath<T, Separator = '.'>

This commit is contained in:
T. R. Bernstein
2025-07-15 07:44:21 +02:00
parent 0cbc6d41a4
commit eac7768bfb
3 changed files with 26 additions and 0 deletions

View File

@@ -34,6 +34,12 @@ The types included in this library are categorized by their purpose.
[`OptionalKeysOf<T>`]: src/optional-keys-of.ts
#### Conversion Types
| Type | Description |
| --------------------------------- | ------------------------------------------------------------------ |
| [`KeyPath<T, Separator = '.'>`][] | Converts a `Separator` separated string into a tuple of its parts. |
#### Combination Types
| Type | Description |

View File

@@ -0,0 +1,9 @@
import type { If } from './if.js'
import type { IsEmptyString } from './is-empty-string.js'
export type KeyPath<
P extends string,
Separator extends string = '.'
> = P extends `${infer Key}${Separator}${infer Rest}`
? [Key, ...KeyPath<Rest, Separator>]
: If<IsEmptyString<P>, [], [P]>

View File

@@ -0,0 +1,11 @@
import type { KeyPath } from '@/key-path.js'
import { expect } from 'tstyche'
expect<KeyPath<''>>().type.toBe<[]>()
expect<KeyPath<'Key'>>().type.toBe<['Key']>()
expect<KeyPath<'Key.Path'>>().type.toBe<['Key', 'Path']>()
expect<KeyPath<'Key.Path', '-'>>().type.toBe<['Key.Path']>()
expect<KeyPath<'Key.Path-One', '-'>>().type.toBe<['Key.Path', 'One']>()
expect<KeyPath<any>>().type.toBe<[] | [string]>()
expect<KeyPath<never>>().type.toBeAssignableWith<never>()