Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Provides additional types and type adjusted utilities for `typescript`
- `Except<T, K>`: Deprecated. Same as `Omit<T, K>`.
- `ExcludePropType<T, U>`: excludes type `U` from properties in `T`.
- `KeyofOptional<T>`: `keyof` that works with `Record<any, any> | undefined`.
- `KnownKeys<T>`: extract known (defined) keys from type `T`.
- `Omit<T, K>`: From `T`, pick a set of properties whose keys are not in the union `K`. This is the opposite of `Pick<T, K>`.
- `PartialExcept<T, U>`: Deprecated. Same as `PartialOmit<T, U>`.
- `PartialOmit<T, U>`: makes the properties not specified in `U` becomes optional.
Expand Down
39 changes: 39 additions & 0 deletions src/KnownKeys.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { assertType, KnownKeys } from '.'

test('pick out only known keys', () => {
type A = {
a?: boolean,
b?: number,
[k: string]: any,
}

const input: A = {}
const actual = getKnownKeys(input)
assertType<'a' | 'b'>(actual)
})

test('primitive type yields never', () => {
assertType.isNever(getKnownKeys(undefined))
assertType.isNever(getKnownKeys(true))
assertType.isNever(getKnownKeys(false))
assertType.isNever(getKnownKeys(null))
assertType.isNever(getKnownKeys('str'))
assertType.isNever(getKnownKeys(1))
assertType.isNever(getKnownKeys({}))
assertType.isNever(getKnownKeys([]))
})

test('literal gets keys', () => {
assertType<'a'>(getKnownKeys({ a: 1 }))
})

test('empty record yields never', () => {
const x: Record<any, any> = {}
const actual = getKnownKeys(x)
assertType.isNever(actual)
})


function getKnownKeys<T>(_value: T): KnownKeys<T> {
return {} as any
}
7 changes: 7 additions & 0 deletions src/KnownKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// by Klaus Meinhardt @ajafff
// known from Gerrit Birkeland @Gerrit0
// https://github.com/Microsoft/TypeScript/issues/25987#issuecomment-408339599
// https://github.com/microsoft/TypeScript/issues/25987#issuecomment-441224690
export type KnownKeys<T> = {
[K in keyof T]: string extends K ? never : number extends K ? never : K
} extends { [_ in keyof T]: infer U } ? ({} extends U ? never : U) : never;
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export * from './JSONTypes';
export * from './KeyofOptional';
export * from './KeysWithDiffType';
export * from './KeyTypes';
export * from './KnownKeys';
export * from './literalArray';
export * from './mapKey';
export * from './mapSeries';
Expand Down