Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
7
Help us understand the problem. What is going on with this article?

More than 3 years have passed since last update.

@kurogelee

TypeScriptでタプルへの型推論を行う方法

TypeScriptで以下のようなコードでタプルを定義しようとしても、[string, number]型ではく(string|number)[]のような共用体(Union)の配列と型推論されてしまいます。

notuple.ts
const tupleStrNum = ["X", 2]; // (string|number)[]

以下のように型定義をすることもできますが

tuple.ts
const tupleStrNum = ["X", 2] as [string, number];
// or
const tupleStrNum: [string, number] = ["X", 2];

以下のような関数を定義しておくことで

util.ts
export function tuple<T1, T2>(t1: T1, t2: T2): [T1, T2];
export function tuple<T1, T2, T3>(t1: T1, t2: T2, t3: T3): [T1, T2, T3];
export function tuple(...args: any[]) {
    return args;
}

以下のようにしてタプルへの型推論を行うことができます。

tuple.ts
import { tuple } from "./util";

const tupleStrNum = tuple("X", 2); // [string, number]
7
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
7
Help us understand the problem. What is going on with this article?