-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(types): add PickAny type, symmetric with PickOne
- Loading branch information
1 parent
b18f4e6
commit 71cb283
Showing
4 changed files
with
76 additions
and
6 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import { PickAny } from './PickAny'; | ||
|
||
describe('PickAny', () => { | ||
it('should constrain type correctly', async () => { | ||
const findFlowers = async ( | ||
input: PickAny<{ | ||
color: { | ||
petals: string; | ||
}; | ||
size: { | ||
choice: 'LARGE' | 'SMALL'; | ||
}; | ||
}>, | ||
) => { | ||
// ... | ||
}; | ||
|
||
// you can find by color | ||
await findFlowers({ | ||
color: { | ||
petals: 'white', | ||
}, | ||
}); | ||
|
||
// you can find by size | ||
await findFlowers({ | ||
size: { | ||
choice: 'LARGE', | ||
}, | ||
}); | ||
|
||
// you can find by both | ||
await findFlowers({ | ||
color: { | ||
petals: 'white', | ||
}, | ||
size: { | ||
choice: 'LARGE', | ||
}, | ||
}); | ||
|
||
// you can't find by neither | ||
await findFlowers({ | ||
// @ts-expect-error - cant be neither | ||
size: {}, | ||
}); | ||
}); | ||
}); |
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,14 @@ | ||
/** | ||
* creates a type which requires specifying at least one, or more, key of an object | ||
* | ||
* ref: | ||
* - https://stackoverflow.com/a/49725198/3068233 | ||
*/ | ||
export type PickAny<TObj, TKeys extends keyof TObj = keyof TObj> = Pick< | ||
TObj, | ||
Exclude<keyof TObj, TKeys> | ||
> & | ||
{ | ||
[K in TKeys]-?: Required<Pick<TObj, K>> & | ||
Partial<Pick<TObj, Exclude<TKeys, K>>>; | ||
}[TKeys]; |
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