10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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]
10
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?