feat(typescript-types): Add KeyPath<T, Separator = '.'>
This commit is contained in:
@@ -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 |
|
||||
|
||||
9
packages/typescript-types/src/key-path.ts
Normal file
9
packages/typescript-types/src/key-path.ts
Normal 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]>
|
||||
11
packages/typescript-types/test/key-path.tst.ts
Normal file
11
packages/typescript-types/test/key-path.tst.ts
Normal 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>()
|
||||
Reference in New Issue
Block a user