TypeScriptのTuple型
簡単な例
type A = [string, number]
type A = [1,2,3]
type A = []
0要素のtuple
可変長のものも定義できる
optionalなものも定義できる
type A = [string, number?];
['hoge', 2]
も ['hoge']
も満たす
optionalなものは複数あってもいい
type A = [string, number?, boolean?];
optionalなものは、そうでない要素より後ろにないといけない
type E = [string?, number];
これはerrorになる
可変長のTuple型を定義できる
...T[]
という構文で書く
これは、普通の T[]
と同じ様に、0個以上の配列型を表す
type A = [number, ...string[]]
最初の要素が number
で、残りが string
のtuple
ts// ...string[]は、0個の要素も満たす
type A = [1, ...string[]];
const a: A = [1];
type A = [...string[], number]
前に置いてもいい
type A = [2, 'hoge', ...string[], boolean];
割と何でも書ける
可変長のものは2つ以上は書けない
type E = [boolean, ...string[], ...number[]];
これはerrorになる
関数の引数に使える
普通に
tstype Args = [string, number, boolean];
const func = (...args: Args) => args[1];
可変長引数
tstype Args = [string, ...number[]];
const func = (f: string, ...args: Args) => args[0]
これは、 const func = (foo: string, ...bar: number[]) => bar[0];
を引数だけ別で定義した感じ
tsfunction f4(t: [string?]) {
let x = t[0]; // string | undefined
t[0] = 'hello';
t[0] = undefined; // Error, 'undefined' not assignable to 'string'
}
関連
参考