他のいくつかのオプションパラメータを省略してオプションパラメータを渡す方法は?


282

次の署名があるとします。

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
}

パラメータを指定せerror() ずにtitleautoHideAfter言うように設定して関数を呼び出すにはどうすればよい1000ですか?

回答:


307

ドキュメントで指定されているように、次を使用しますundefined

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter? : number);
}

class X {
    error(message: string, title?: string, autoHideAfter?: number) {
        console.log(message, title, autoHideAfter);
    }
}

new X().error("hi there", undefined, 1000);

遊び場リンク


6
@ BBi7あなたはドキュメントを誤解していると思います。?機能で追加された定義が、質問は実際にについてです呼び出し機能を。
トーマス

こんにちは@Thomas私はドキュメントを完全に理解しており、あなたは?関数定義のパラメータの後。しかし、オプションのパラメーターを使用して関数を呼び出すことに関連して、該当しない場合はundefinedを渡すことを想定しています。私は通常、オプションのパラメーターを終了パラメーターとして作成する方法を見つけようとしているので、未定義に対して渡すことはできません。しかし、明らかに多くの場合、未定義または真実でないものを渡す必要があります。私が最初に投稿したときに何を参照していたのかわかりません。編集されたかどうかはわかりませんが、現在表示されているものは正しく修正されています。
BBi7、2018

2
@ BBi7最近の編集はありません。わかりました。気にしないでください:)(undefined引数を完全に省略した場合と同じ動作を得るには、実際にパスする必要があることに注意してください。TypeScript は実際にはvoid 0どちらが安全な書き込み方法であるかを比較するため、「真実ではないもの」は機能しませんundefined。 )
トーマス

71

残念ながら、TypeScriptにはこのようなものはありません(詳細はこちら:https : //github.com/Microsoft/TypeScript/issues/467

しかし、これを回避するには、パラメーターをインターフェイスに変更できます。

export interface IErrorParams {
  message: string;
  title?: string;
  autoHideAfter?: number;
}

export interface INotificationService {
  error(params: IErrorParams);
}

//then to call it:
error({message: 'msg', autoHideAfter: 42});

教えてください、エラーメソッドを次のように呼び出すことができますか、error({message: 'test'})、私たちはできないので、error({message: 'test'、autoHideAFter:undefined})ですが、私が期待しているのはerror(message)です。他のパラメーターを渡さなかった場合は、デフォルトのパラメーターから値を取得します。
Cegone

37

オプションの変数byを使用できます。?複数のオプションの変数byがある場合は...、例を示します。

function details(name: string, country="CA", address?: string, ...hobbies: string) {
    // ...
}

上記では:

  • name 必要とされている
  • country 必須であり、デフォルト値があります
  • address オプションです
  • hobbies オプションのパラメータの配列です

2
趣味を配列として入力するべきではありませんか?
ProgrammerPer

4
この回答には役立つ情報がありますが、質問には回答しません。問題は、私が見ているように、いくつかのオプションのパラメーターをバイパス/スキップして、特定のパラメーターのみを設定する方法です。
MaxB 2019年

2
国は必須ではありません。これは、未定義ではなくデフォルト値「CA」を持つオプションのパラメーターです。それが必要な場合、デフォルト値を提供する意味は何ですか?
Anand Bhushan

19

別のアプローチは:

error(message: string, options?: {title?: string, autoHideAfter?: number});

したがって、titleパラメータを省略したい場合は、次のようにデータを送信します。

error('the message', { autoHideAfter: 1 })

他のパラメーターを送信せずにパラメーターを追加できるので、このオプションを使用したいと思います。


また、デフォルト値をどのように渡しますtitleか?
Dan Dascalescu

13

これは@Broccoの回答とほとんど同じですが、少しひねりを加えています。オブジェクトではオプションのパラメーターのみを渡します。(また、paramsオブジェクトをオプションにします)。

最終的には、Pythonの** kwargsのようなものになりますが、正確ではありません。

export interface IErrorParams {
  title?: string;
  autoHideAfter?: number;
}

export interface INotificationService {
  // make params optional so you don't have to pass in an empty object
  // in the case that you don't want any extra params
  error(message: string, params?: IErrorParams);
}

// all of these will work as expected
error('A message with some params but not others:', {autoHideAfter: 42});
error('Another message with some params but not others:', {title: 'StackOverflow'});
error('A message with all params:', {title: 'StackOverflow', autoHideAfter: 42});
error('A message with all params, in a different order:', {autoHideAfter: 42, title: 'StackOverflow'});
error('A message with no params at all:');

5

インターフェイスで複数のメソッドシグネチャを指定してから、クラスメソッドで複数のメソッドオーバーロードを持つことができます。

interface INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter: number);
}

class MyNotificationService implements INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter?: number);
    error(message: string, param1?: (string|number), param2?: number) {
        var autoHideAfter: number,
            title: string;

        // example of mapping the parameters
        if (param2 != null) {
            autoHideAfter = param2;
            title = <string> param1;
        }
        else if (param1 != null) {
            if (typeof param1 === "string") {
                title = param1;
            }
            else {
                autoHideAfter = param1;
            }
        }

        // use message, autoHideAfter, and title here
    }
}

これらすべてが機能します:

var service: INotificationService = new MyNotificationService();
service.error("My message");
service.error("My message", 1000);
service.error("My message", "My title");
service.error("My message", "My title", 1000);

...とのerrorメソッドにINotificationServiceは次のオプションがあります:

過負荷インテリセンス

遊び場


9
私はこれに対してお勧めしますが、代わりにオブジェクトを渡して、これらのパラメーターをそのオブジェクトのプロパティとして配置します...作業が大幅に減り、コードが読みやすくなります。
David Sherret、2016年

2

エラー引数に基づいて1つのオブジェクトパラメータを受け入れるヘルパーメソッドを作成できます。

 error(message: string, title?: string, autoHideAfter?: number){}

 getError(args: { message: string, title?: string, autoHideAfter?: number }) {
    return error(args.message, args.title, args.autoHideAfter);
 }

-1

タイトルをnullに設定してみてください。

これでうまくいきました。

error('This is the ',null,1000)

3
このパラメーターは、関数パラメーターにnullを送信したときに関数パラメーターにデフォルト値が設定されている場合、そのデフォルト値に設定されないため、機能しません
Okan SARICA

-2

インターフェースなしでこれを行うことができます。

class myClass{
  public error(message: string, title?: string, autoHideAfter? : number){
    //....
  }
}

?演算子をオプションのパラメーターとして使用します。


しかし、これはあなたに指定する方法を許可しないmessageautoHideAfter
Simon_Weaver

3
質問に答えないか、読んでいません。彼は、2つ目のパラメーターのみを入力したい場合は、最初のオプションを指定する必要なしに、複数のオプションパラメーターを使用してメソッドを呼び出す方法を知りたいと考えています。
Gregfr 2018年
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.