Declare function with a Readonly return type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 24, 2022

banner

Photo from Unsplash

Declare function with a Readonly return type in TypeScript #

Use the Readonly utility type to declare a function with a readonly return type, e.g. function getArr(): Readonly<string[]> {}. The Readonly utility type constructs a type with all properties set to readonly. The properties of the constructed type cannot be reassigned.

index.ts
function getArr(): Readonly<string[]> { return ['a', 'b', 'c']; } function getObj(): Readonly<{ name: string }> { return { name: 'Tom' }; } function getSet(): ReadonlySet<string> { return new Set(['a', 'b', 'c']); } function getMap(): ReadonlyMap<string, string> { return new Map([['name', 'Tom']]); }

We used the Readonly utility type to type a function whose return value only permits reading.

You can set the return type of a function right after its parameter list.

The 2 functions in the following code snippet have the same return type - a readonly array of strings.

index.ts
function getArr(): Readonly<string[]> { return ['a', 'b', 'c']; } function getArr2(): ReadonlyArray<string> { return ['c', 'd', 'e']; }

If you try to change a value in the readonly array, you'd get an error.

index.ts
function getArr(): Readonly<string[]> { return ['a', 'b', 'c']; } const a = getArr(); // ⛔️ Index signature in type 'readonly string[]' // only permits reading.ts(2542) a[0] = 'z';

The same is the case when working with readonly objects.

index.ts
function getObj(): Readonly<{ name: string }> { return { name: 'Tom' }; } const obj = getObj(); // ⛔️ Error: Property 'age' does not exist // on type 'Readonly<{ name: string; }>'.ts(2339) obj.age = 30;

When working with Set or Map objects, make sure to use the corresponding utility types - ReadonlySet and ReadonlyMap.

index.ts
function getSet(): ReadonlySet<string> { return new Set(['a', 'b', 'c']); } function getMap(): ReadonlyMap<string, string> { return new Map([['name', 'Tom']]); }

The first type we passed to the ReadonlyMap utility type is the type for the keys, and the second - for the values.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.