programing

Typescript 매개 변수 이름에서 물음표는 무엇입니까?

lastcode 2023. 3. 18. 08:40
반응형

Typescript 매개 변수 이름에서 물음표는 무엇입니까?

export class Thread {
  id: string;
  lastMessage: Message;
  name: string;
  avatarSrc: string;

  constructor(id?: string,
              name?: string,
              avatarSrc?: string) {
    this.id = id || uuid();
    this.name = name;
    this.avatarSrc = avatarSrc;
  }
}

id?뭐야??뭐에 대해서요?

이는 파라미터를 옵션으로 표시하기 위한 것입니다.

  • TypeScript 핸드북 https://www.typescriptlang.org/docs/handbook/2/functions.html#optional-parameters
  • TypeScript 딥 다이브 https://basarat.gitbook.io/typescript/type-system/functions#optional-parameters

parameter?: type의 줄임말이다parameter: type | undefined

그럼 차이점은 무엇일까요?물음표는 "선택 사항"을 의미합니다.
더 정확히 말하면parameter?: type동등하다parameter: type | undefined = undefined

이것은 변수를 Optional type으로 만들기 위한 것입니다.그렇지 않으면 선언된 변수는 이 변수를 사용하지 않으면 "정의되지 않음"으로 표시됩니다.

export interface ISearchResult {  
  title: string;  
  listTitle:string;
  entityName?: string,
  lookupName?:string,
  lookupId?:string  
}

?파라미터는 옵션 파라미터를 나타냅니다.Typescript 컴파일러에서는 이 파라미터를 입력할 필요가 없습니다.상세한 것에 대하여는, 다음의 코드 예를 참조해 주세요.

// baz: number | undefined means: the second argument baz can be a number or undefined

// = undefined, is default parameter syntax, 
// if the parameter is not filled in it will default to undefined

// Although default JS behaviour is to set every non filled in argument to undefined 
// we need this default argument so that the typescript compiler
// doesn't require the second argument to be filled in
function fn1 (bar: string, baz: number | undefined = undefined) {
    // do stuff
}

// All the above code can be simplified using the ? operator after the parameter
// In other words fn1 and fn2 are equivalent in behaviour
function fn2 (bar: string, baz?: number) {
    // do stuff
}



fn2('foo', 3); // works
fn2('foo'); // works

fn2();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.


fn1('foo', 3); // works
fn1('foo'); // works

fn1();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.

TypeScript 4.7 현재 컴파일러는 다음과 같은 시나리오를 처리합니다.

interface OptTest {
  test: string
  test2: string
  test3?: string
  test4?: string | null
  test5: string | null
  test6: null
}

const testVar: OptTest = {} 
// Type '{}' is missing the following 
// properties from type 'OptTest': test, test2, test5, test6

언급URL : https://stackoverflow.com/questions/37632760/what-is-the-question-mark-for-in-a-typescript-parameter-name

반응형