Created
July 25, 2026 10:49
-
-
Save MaxGraey/1f99c21001e4a3c3d7586895b136ff9a to your computer and use it in GitHub Desktop.
Non-Empty type util for typescript
This file contains hidden or 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
| declare const nonEmpty: unique symbol; | |
| type NonEmpty<T> = | |
| T extends string ? T & `${string & {}}${string}` : | |
| T extends readonly unknown[] ? T & { readonly 0: T[0] } : | |
| T extends object ? T & ({} extends T ? { [nonEmpty]: never } : {}) : | |
| never; | |
| const arr: NonEmpty<string[]> = ['foo']; | |
| const obj: NonEmpty<{ x: number }> = { x: 1 }; | |
| const str: NonEmpty<'hello'> = 'hello'; | |
| // Errors: | |
| const emptyArr: NonEmpty<string[]> = []; | |
| const emptyStr: NonEmpty<string> = ''; | |
| const emptyObj: NonEmpty<object> = {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment