Skip to content

Commit

Permalink
feat(types): 新增 DotPath
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 12, 2021
1 parent 24d9e91 commit 2417103
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 4 deletions.
28 changes: 28 additions & 0 deletions src/types/DotPath.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { DotPath, DotPathValue } from './DotPath'
import { expectType } from '../dev'

describe('DotPath', () => {
test('表现正常', () => {
const obj = {
x: {
y: {
z: [0, '1'] as const,
哈哈: 1,
},
},
}
// eslint-disable-next-line
function get<T, P extends DotPath<T>>(
_object: T,
_path: P,
): DotPathValue<T, P> {
return 1 as any
}

const xyz1 = get(obj, 'x.y.z.1')
expectType<typeof xyz1, '1'>()

const xyz哈哈 = get(obj, 'x.y.哈哈')
expectType<typeof xyz哈哈, number>()
})
})
20 changes: 20 additions & 0 deletions src/types/DotPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// ref: https://github.com/ahejlsberg/tsconf2020-demos/blob/master/template/main.ts#L108
type SubKeys<T, K extends string> = K extends keyof T
? `${K}.${DotPath<T[K]>}`
: never

export type DotPath<T> = object extends T
? string
: T extends readonly any[]
? Extract<keyof T, `${number}`> | SubKeys<T, Extract<keyof T, `${number}`>>
: T extends object
? Extract<keyof T, string> | SubKeys<T, Extract<keyof T, string>>
: never

export type DotPathValue<T, Path extends string> = Path extends keyof T
? T[Path]
: Path extends `${infer K}.${infer R}`
? K extends keyof T
? DotPathValue<T[K], R>
: unknown
: unknown
2 changes: 1 addition & 1 deletion src/types/Path.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expectType } from '../dev'
import { Path, PathValue } from './Path'

describe('OneOrMore', () => {
describe('Path', () => {
test('表现正常', () => {
const obj = {
x: {
Expand Down
3 changes: 0 additions & 3 deletions src/types/__expectType__.ts

This file was deleted.

1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export * from './AnyAsyncFunction'
export * from './AnyFunction'
export * from './AnyObject'
export * from './Defined'
export * from './DotPath'
export * from './FirstParameter'
export * from './IsAny'
export * from './IsNever'
Expand Down

0 comments on commit 2417103

Please sign in to comment.