Yesterday, Microsoft announced the release candidate of TypeScript 4.0. And with that comes Labeled Tuple Elements, which is the answer to the title of this post.
Here’s a contrived example. IQuery
. It’s meant to describe the shape of functions that query things. It always returns a promise and takes a Generic to describe what the promise emits (TReturn
). The interface is also flexible enough to take no arguments or an unknown number of arguments (UParams extends any[] = []
).
interface IQuery<TReturn, UParams extends any[] = []> {
(...args: UParams): Promise<TReturn>
}
Leveraging this interface, we’ll write a function that finds a song album by a title and an artist. It returns a promise that emits a single object of type Album
.
type Album = {
title: string
}
Without TypeScript, the function could look like this:
const findSongAlbum = (title, artist) => {
// data fetching code...
const albumName = '1989';
return Promise.resolve({
title: albumName
});
}
With TypeScript, and leveraging the IQuery
interface, you’d pass in Album
type as the first Generic parameter to ensure the shape of what the promise emits always matches Album
type.
const findSongAlbum: IQuery<Album> = (title, artist) => {
// data fetching code...
const albumName = '1989';
return Promise.resolve({
title: 1989
});
}
#web-development #javascript #tuples #typescript