3
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

コード

2値の型引数を持つTargetTypeFuncImpl があるとき、VariableLengthTypeFunc が再帰的に適用するようになっています

type TargetType = any; // 好きな型を入れてください
type VariableLengthTypeFunc<T extends TargetType[]> = T extends [any, ...(infer A)]
? A extends TargetType[]
  ? A[1] extends undefined 
    ? TargetTypeFuncImpl<T[0], A[0]> // 3番めの要素が空の場合再起の底なので、2値の合成を行います
    : TargetTypeFuncImpl<T[0], VariableLengthTypeFunc<A>> // そうでなければ、先頭とそれ以外の要素で合成します
  : never
: never

// 具体的にやりたい型の処理を書いてください
type TargetTypeFuncImpl<T1, T2> = T1 | T2;

----
type Test = TargetTypeFunc<[number, string, Object]>; // => number | TargetTypeFuncImpl<string, Object>
const test1: Test = 0; // => valid
const test2: Test = ""; // => valid
const test: Test = null; // => invalid

type NullableTest = TargetTypeFunc<[number, string, Object, null]>; // => number | TargetTypeFuncImpl<string, TargetTypeFuncImpl<Object, null>>
const test1: NullableTest = 0; // => valid
const test2: NullableTest = ""; // => valid
const test: NullableTest = null; // => valid
3
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
3
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?