search
LoginSignup
1
Help us understand the problem. What are the problem?

posted at

TypeScriptで可変長のジェネリクスを作る

コード

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

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
What you can do with signing up
1
Help us understand the problem. What are the problem?