0
1

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 1 year has passed since last update.

[TypeScript]タプル型で可変長とオプショナルの併用はできない

Posted at

小ネタです。

@uhyoさんのTypeScriptの型入門のタプル型の説明を拝見して試した内容のメモです。

可変長のタプル型の宣言


//uhyoさんのサンプルコード
type NumAndStrings = [number, ...string[]];
type StrsAndNumber = [...string[], number];

//可変長を間に挟めるか確認(OK)
type NumAndStringsAndNum = [number, ...string[], number];

//代入式
const a1: NumAndStrings = [3, 'foo', 'bar'];
const a2: StrsAndNumber = ['foo', 'bar', 3];
const a3: NumAndStringsAndNum = [1, 'foo', 'bar', 3];

オプショナルのタプル型の宣言


//uhyoさんのサンプルコード
type T = [string, number?];

const t1: T = ['foo'];
const t2: T = ['foo', 3];

//オプショナルを複数宣言(OK)
// →オプショナルが末尾に固まっていれば良い
type U = [string, number?, string?, number?];

const u1: U = ['文字列', 1];
const u2: U = ['文字列', 1, '文字列2'];
const u3: U = ['文字列', '文字列2']; //NG
  //Type 'string' is not assignable to type 'number'.(2322)
  //中間(2個めのnumber?)の省略はできない。

本題:可変長とオプショナルを併用したタプル型の宣言(NG)


//可変長とオプショナルを併用したタプル型の宣言は...
type NumAndStringsWithOptionalNumber = [number, ...string[], number?];
  //An optional element cannot follow a rest element.(1266)
  //...と言われてしまう(number?部分)

//なので、こういう事はできない
const a1: NumAndStringsWithOptionalNumber = [3, 'foo', 'bar'];
const a2: NumAndStringsWithOptionalNumber = [3, 'foo', 'bar', 10];

可変長を間に挟み込めるなら行けるかも!?...と思いましたがダメでした。
いるか!?」って聞かれると...私は使う機会はなさそうです(^^;

以上、現場からお伝えしました!

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?