ウェブサイト検索

typescript - ジェネリック型定義で等号付きの extends 制約はどのような効果がありますか?


私はこの extends 構文を見たことがあります:

export type MyType<Data extends Base = Base> = { data: Data }

Base=Base の使用は何をしますか?

ジェネリクスに関するTypeScriptのドキュメントはそれを説明していません。

回答 #1

デフォルトのジェネリックパラメータ - ドキュメント

これにより、ジェネリックパラメータなしでMyTypeを呼び出すことができます。

type Base = { tag: 'Base' }

export type MyType<Data extends Base = Base> = { data: Data }

// type WithArgument = {
//     data: {
//         tag: 'Base';
//         name: 'John';
//     };
// }
type WithArgument = MyType<{ tag: 'Base', name: 'John' }>

// { data: Base; }
type Result = MyType 

純粋なJSの例え:

const myType = (arg = { tag: 'Base' }) => arg
const result = myType() // { tag: 'Base' }

この Data extends Base=Base は次の意味です:

  1. Data は Base を拡張するべきです
  2. データが提供されない場合、デフォルトでBaseを使用してください

これは二つの部分に分けることができる方法です:

  1. Data extends Base
  2. Data = Base

あなたは extends word から離して Base=Base を個別に読むべきではありません

回答 #2

これは汎用型のデフォルト値です。例えば:

type MyType<Data extends Object = String> = { data: Data }

let test: MyType = {data: 'test'}; // Same as MyType<string>

console.log(typeof test.data); // prints string

let test2: MyType<Number> = {data: 5}; 

console.log(typeof test2.data); // prints number