With TypeScript v3.4 const assertions:

export const AVAILABLE_STUFF = <const> ['something', 'else'];
export type Stuff = typeof AVAILABLE_STUFF[number];
Answer from Archit Garg on Stack Overflow
🌐
W3Schools
w3schools.com › typescript › typescript_arrays.php
TypeScript Arrays
TypeScript can infer the type of an array if it has values. const numbers = [1, 2, 3]; // inferred to type number[] numbers.push(4); // no error // comment line below out to see the successful assignment numbers.push("2"); // Error: Argument ...
🌐
TypeScript Tutorial
typescripttutorial.net › home › typescript tutorial › typescript array type
TypeScript Array Type
August 24, 2024 - It’s equivalent to the following: let scores : (string | number)[]; scores = ['Programming', 5, 'Software Design', 4]; Code language: TypeScript (typescript) In TypeScript, an array is an ordered list of values. Use the let arr: type[] syntax to declare an array of a specific type.
Discussions

Is it possible to create a typescript type from an array? - Stack Overflow
I often use code such as export type Stuff = 'something' | 'else' export const AVAILABLE_STUFF: Stuff[] = ['something', 'else'] This way I can both use the type Stuff, and iterate over all the More on stackoverflow.com
🌐 stackoverflow.com
Array<Type> VS Type[] in Typescript - Stack Overflow
As far as I know a property's type can be defined in two ways when it's an array: property_name: type where type can be either Array Array // etc. (e.g. let prop1: Arra... More on stackoverflow.com
🌐 stackoverflow.com
Defining array with multiple types in TypeScript - Stack Overflow
I have an array of the form: [ 1, "message" ]. How would I define this in TypeScript? More on stackoverflow.com
🌐 stackoverflow.com
Best way to declare an array type in TypeScript? - Stack Overflow
What would be the best or most common way to declare an array type in TypeScript? There are several ways to do it but I'm not sure if it matters how you do it. This is how I created the array type More on stackoverflow.com
🌐 stackoverflow.com
🌐
Tutorial Teacher
tutorialsteacher.com › typescript › typescript-array
TypeScript Arrays
This method is similar to how you would declare arrays in JavaScript. let fruits: string[] = ['Apple', 'Orange', 'Banana']; 2. Using a generic array type, Array<elementType>. let fruits: Array<string> = ['Apple', 'Orange', 'Banana']; Both methods produce the same output. Of course, you can always initialize an array like shown below, but you will not get the advantage of TypeScript's type system.
🌐
TkDodo
tkdodo.eu › blog › array-types-in-type-script
Array Types in TypeScript
August 19, 2023 - To be clear, there is absolutely no functional difference between the two notations. It seems that its just personal preference about which one to choose. Whatever you do, please make sure to turn on the array - type (opens in a new window) eslint rule to use either one of the notations consistently.
🌐
Ultimate Courses
ultimatecourses.com › blog › typing-arrays-typescript
Typing Arrays in TypeScript - Ultimate Courses
January 12, 2023 - There are many ways in TypeScript to type a property as an array, or contains an array of “something”. These ways of declaring an array type include generic types, array types and type assertions - which we’ll uncover in this article.
Top answer
1 of 3
48

With TypeScript v3.4 const assertions:

export const AVAILABLE_STUFF = <const> ['something', 'else'];
export type Stuff = typeof AVAILABLE_STUFF[number];
2 of 3
17

One built-in option would be to use an enum instead of the type and array approach.

export enum Stuff {
    something = 'something',
    else = 'else',
}

export const AVAILABLE_STUFF: Stuff[] = Object.values(Stuff);

Another option is to extract the type from the type of AVAILABLE_STUFF. To do this we must force the compiler to infer a tuple of string literals for AVAILABLE_STUFF. This can be done in 3.4 with as const or before 3.4 using an extra function. After AVAILABLE_STUFF is a tuple type we can just use a type query to get the type of the elements:

export const AVAILABLE_STUFF = (<T extends string[]>(...o: T)=> o)('something', 'else'); // typed as ["something", "else"]
// export const AVAILABLE_STUFF = ['something', 'else'] as const; // typed as ["something", "else"]  in 3.4
export type Stuff = typeof AVAILABLE_STUFF[number] //"something" | "else"

A few explanations of the above code. typeof AVAILABLE_STUFF gives us the type of the constant (["something", "else"]) to get the [number] is called a type query and will give us the type of an item in the tuple.

The (<T extends string[]>(...o: T)=> o) is just an IIFE we use to force the compiler to infer a string literal tuple type. It has to be generic as the compiler will only infer literal types and tuples in certain cases (a type parameter with a constraint of string being one of them). The as const version is what I would recommend using when it becomes available as it is more readable.

🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › everyday-types.html
TypeScript: Documentation - Everyday Types
When a function appears in a place where TypeScript can determine how it’s going to be called, the parameters of that function are automatically given types. ... Even though the parameter s didn’t have a type annotation, TypeScript used the types of the forEach function, along with the inferred type of the array, to determine the type s will have.
Find elsewhere
🌐
W3Schools Blog
w3schools.blog › home › typescript array
TypeScript array - W3Schools.blog
March 8, 2018 - A TypeScript Array object represents a collection of elements of the same type. By using array literals. By using Array() constructor. Using an array literal is the simplest way to create a TypeScript Array.
🌐
Medium
jng15.medium.com › typescript-basics-iii-arrays-36750905ee15
TypeScript Basics (III): Arrays. Type annotation for arrays can be… | by James Ng | Medium
November 16, 2022 - If an array with the same (ordered) data types and length is assigned to a tuple variable, TS will throw a fit. Remember, it is pretty strict. ... While TypeScript can infer variable types from initial values and return statements, things are slightly different when dealing with arrays. Let’s say we declare a variable nums as the following: ... This looks like it could possibly be inferred as an array type number[ ] or tuple type [ number, number, number ]. TypeScript gives the nod to the less restrictive type — the array type.
🌐
W3Schools
w3schools.com › js › js_typed_arrays.asp
W3Schools.com
Fixed Length: Typed Arrays cannot be dynamically resized using methods like push() or pop(). Type Restriction: Elements must adhere to the specified data type of the typed array.
🌐
TypeScript ESlint
typescript-eslint.io › rules › array-type
array-type | typescript-eslint
... Some problems reported by this rule are automatically fixable by the --fix ESLint command line option. TypeScript provides two equivalent ways to define an array type: T[] and Array<T>. The two styles are functionally equivalent.
🌐
2ality
2ality.com › 2020 › 02 › typing-arrays-typescript.html
Typing Arrays in TypeScript
February 24, 2020 - Both array type literals and Array require all elements to have the same type.
🌐
W3Schools
w3schools.com › typescript › index.php › typescript_arrays.php
TypeScript Tutorial
HTML CSS JAVASCRIPT SQL PYTHON ... DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST · TS HOME TS Introduction TS Get Started TS Simple Types TS Special Types TS Arrays TS Tuples TS Object Types TS Enums TS Aliases & Interfaces TS Union Types TS Functions TS Casting TS Classes TS Basic Generics TS Utility Types TS Keyof TS Null TS Definitely Typed TS 5 ...
Top answer
1 of 4
383

TypeScript 3.4+

TypeScript version 3.4 has introduced so-called **const contexts**, which is a way to declare a tuple type as immutable and get the narrow literal type directly (without the need to call a function like shown below in the 3.0 solution).

With this new syntax, we get this nice concise solution:

const furniture = ['chair', 'table', 'lamp'] as const;
type Furniture = typeof furniture[number];

More about the new const contexts is found in this PR as well as in the release notes.

TypeScript 3.0+

With the use of generic rest parameters, there is a way to correctly infer string[] as a literal tuple type and then get the union type of the literals.

It goes like this:

const tuple = <T extends string[]>(...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');
type Furniture = typeof furniture[number];

More about generic rest parameters

2 of 4
22

This answer is out of date; see @ggradnig's answer.

The best available workaround:

const furnitureObj = { chair: 1, table: 1, lamp: 1 };
type Furniture = keyof typeof furnitureObj;
const furniture = Object.keys(furnitureObj) as Furniture[];

Ideally we could do this:

const furniture = ['chair', 'table', 'lamp'];
type Furniture = typeof furniture[number];

Unfortunately, today furniture is inferred as string[], which means Furniture is now also a string.

We can enforce the typing as a literal with a manual annotation, but it brings back the duplication:

const furniture = ["chair", "table", "lamp"] as ["chair", "table", "lamp"];
type Furniture = typeof furniture[number];

TypeScript issue #10195 tracks the ability to hint to TypeScript that the list should be inferred as a static tuple and not string[], so maybe in the future this will be possible.

🌐
GitHub
github.com › microsoft › TypeScript › issues › 28046
Creating types from values in array · Issue #28046 · microsoft/TypeScript
October 22, 2018 - Link to playground http://www.typescriptlang.org/play/#src=let vals1 = ['A', 'B'] type Foo1 = OneOf<vals1> // Is there a way of doing this?
Author   G2Jose
🌐
W3Schools
w3schools.com › typescript › typescript_tuples.php
TypeScript Tuples
Because of the structure we know our first value in our list will be a certain value type in this case a string and the second value a function. Named tuples allow us to provide context for our values at each index. const graph: [x: number, y: number] = [55.2, 41.3]; Named tuples provide more context for what our index values represent. Since tuples are arrays we can also destructure them.