Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
- Loading branch information
1 parent
b9a23df
commit 2ee5957
Showing
4 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
Create a union of the given object's values, and optionally specify which keys to get the values from. | ||
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31438) if you want to have this type as a built-in in TypeScript. | ||
@example | ||
``` | ||
// data.json | ||
{ | ||
'foo': 1, | ||
'bar': 2, | ||
'biz': 3 | ||
} | ||
// main.ts | ||
import {ValueOf} from 'type-fest'; | ||
import data = require('./data.json'); | ||
export function getData(name: string): ValueOf<typeof data> { | ||
return data[name]; | ||
} | ||
export function onlyBar(name: string): ValueOf<typeof data, 'bar'> { | ||
return data[name]; | ||
} | ||
// file.ts | ||
import {getData, onlyBar} from './main'; | ||
getData('foo'); | ||
//=> 1 | ||
onlyBar('foo'); | ||
//=> TypeError ... | ||
onlyBar('bar'); | ||
//=> 2 | ||
``` | ||
*/ | ||
export type ValueOf<ObjectType, ValueType extends keyof ObjectType = keyof ObjectType> = ObjectType[ValueType]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import {expectType, expectError} from 'tsd'; | ||
import {ValueOf} from '..'; | ||
|
||
const value: ValueOf<{a: 1; b: 2; c: 3}> = 3; | ||
const valueRestricted: ValueOf<{a: 1; b: 2; c: 3}, 'a'> = 1; | ||
|
||
expectType<1 | 2 | 3>(value); | ||
expectError<4>(value); | ||
|
||
expectType<1>(valueRestricted); | ||
expectError<2>(valueRestricted); | ||
expectError<4>(valueRestricted); |