다른 선택적 매개 변수를 생략하면서 선택적 매개 변수를 전달하는 방법은 무엇입니까?


282

다음과 같은 서명이 주어집니다.

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

매개 변수를 지정 error() 하지 않고 say로 title설정 하여 함수를 어떻게 호출 할 수 있습니까?autoHideAfter1000

답변:


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를 전달한다고 가정합니다. 나는 일반적으로 선택적 매개 변수를 최종 매개 변수로 만드는 방법을 찾으려고 노력하므로 정의되지 않은 vs.를 전달할 수 없습니다. 그러나 분명히 많은 것이 있다면 정의되지 않은 것이거나 불완전한 것을 전달해야합니다. 내가 처음 게시했을 때 내가 무엇을 말하고 있었는지 잘 모르겠습니다. 의미를 편집했는지 알 수 없지만 이제는 올바르게 표시됩니다.
BBi7

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 메소드를 호출 할 수 있습니까, 생각할 수 없으므로 error ({message : 'test', autoHideAFter : undefined})이지만 내가 기대하는 것은 error (message)입니다. 다른 매개 변수를 전달하지 않으면 기본 매개 변수에서 값을 가져옵니다.
Cegone

37

에 의해 선택적 변수를 사용할 수 있습니다. ?또는에 의해 여러 개의 선택적 변수가있는 ...경우 :

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

위 :

  • name 필요하다
  • country 필수이며 기본값이 있습니다
  • address 선택 사항입니다
  • hobbies 선택적 매개 변수의 배열입니다

2
취미는 배열로 입력해서는 안됩니까?
ProgrammerPer

4
이 답변에는 유용한 정보가 있지만 질문에 대답하지는 않습니다. 문제는 내가 볼 수 있듯이 여러 선택적 매개 변수를 우회 / 건너 뛰고 특정 매개 변수 만 설정하는 방법입니다.
MaxB

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 객체를 선택적으로 만듭니다.

파이썬의 ** 크 워그와 비슷하지만 정확하게는 아닙니다.

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

2

오류 인수를 기반으로 하나의 객체 매개 변수를 허용하는 도우미 메서드를 만들 수 있습니다

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

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

-1

title을 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
질문에 대답하지 않았거나 읽지 않았습니다. 그는 두 번째 매개 변수 만 입력하려는 경우 첫 번째 옵션을 지정하지 않고도 여러 선택적 매개 변수를 사용하여 메서드를 호출하는 방법을 알고 싶어합니다.
Gregfr
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.