ElementOf type
Reads the item type of an array or tuple, such as the type of a const list of options.
ts
import type { ElementOf } from 'utils';Signature
ts
export type ElementOf<T extends readonly unknown[]> = T[number];Parameters
| Name | Description |
|---|---|
T | The array type. |
Example
ts
const UNITS = ['kn', 'km/h', 'm/s'] as const;
type Unit = ElementOf<typeof UNITS>; // 'kn' | 'km/h' | 'm/s'Tests
Line coverage: 0 %.
- ✅ reads the item type
Source
src/types/element-of.ts (on GitHub)
Source code
ts
/**
* Reads the item type of an array or tuple, such as the type of a `const` list of options.
*
* @template T - The array type.
* @example
* const UNITS = ['kn', 'km/h', 'm/s'] as const;
* type Unit = ElementOf<typeof UNITS>; // 'kn' | 'km/h' | 'm/s'
*/
export type ElementOf<T extends readonly unknown[]> = T[number];Test file
ts
import type { ElementOf } from './element-of';
describe('ElementOf', () => {
it('reads the item type', () => {
expectTypeOf<ElementOf<readonly ['kn', 'm/s']>>().toEqualTypeOf<'kn' | 'm/s'>();
expectTypeOf<ElementOf<number[]>>().toEqualTypeOf<number>();
});
});Keywords: element, of, types, type