[번역] 타입스크립트 면접/인터뷰 질문 시리즈 - 2

minbr0ther·2022년 4월 25일
2

typescript

목록 보기
2/2
post-thumbnail

https://www.interviewbit.com/typescript-interview-questions/
개인공부를 위해 번역이 되었으며, 번역이 틀릴 수 도 있습니다 :)

이 게시물은 시리즈로 이어지며, 이전 게시물을 먼저 확인해주세요.

11. TypeScript에서 never type의 목적을 알려주세요

이름에서 알 수 있듯이 never 은 발생하지 않는 값의 type을 나타냅니다. 예를 들어 값을 반환하지 않거나 항상 예외를 throw하는 함수는 반환 type을 never로 표시할 수 있습니다.

function error(message: string): never {
	throw new Error(message);
}

이미 void가 있는데 왜 never가 필요한지 궁금할 것입니다. 두 유형이 비슷해 보이지만 두 가지 매우 다른 개념을 가지고 있습니다.

// 이 함수는 undefined를 반환합니다.
function greet(name: string) {
	console.log(`Hello, ${name}`);
}

let greeting = greet("David");
console.log(greeting);  // undefined

반대로, 반환값으로 never 타입을 지정한 함수는 절대 반환하지 않습니다. 심지어 undefined값도 반환하지 않습니다. 함수가 절대 유형을 반환하지 않는 두 가지 경우가 있습니다.

  1. 무한 루프(예: while(true){} 유형 루프)

  2. 오류를 발생시키는 함수(예: function foo(){throw new Exception('Error message')}


12. TypeScript에서 enum이 어떻게 작동하는지 설명해주세요.

enum을 사용하면 값이 변하지 않는 상수를 만들 수 있습니다. 숫자 상수 값에 보다 가독성 좋은 이름을 지정하는 방법입니다. enumenum으로 시작하는 키워드로 정의되고 그 뒤에 해당 이름과 멤버가 옵니다.

enum Team {
  Alpha,
  Beta,
  Gamma,
  Delta
}
let t: Team = Team.Delta;

기본적으로 enum은 0부터 번호 매기기를 시작합니다. 해당 멤버에 값을 명시적으로(explicity) 할당하여 기본 번호 매기기를 재정의(override)할 수 있습니다.

TypeScript를 사용하면 다음과 같이 문자열 값으로 열거형을 만들 수도 있습니다.

enum Author {
  Anders = "Anders",
  Hejlsberg = "Hejlsberg"
};

13. typeof 연산자는 무엇인가요? TypeScript에서 어떻게 사용될까요?

JavaScript와 유사하게 TypeScript의 typeof 연산자는 피연산자(operand)의 유형을 문자열로 반환합니다.

console.log(typeof 10);  // "number"

console.log(typeof 'foo');  // "string"

console.log(typeof false);  // "boolean"

console.log(typeof bar);  // "undefined"

TypeScript에서 유형 컨텍스트에서 typeof 연산자를 사용하여 속성 또는 변수의 type을 참조할 수 있습니다.

let greeting = "hello";
let typeOfGreeting: typeof greeting;  // let typeOfGreeting: string과 유사

14. TypeScript의 나머지 매개변수(rest parameters)와 인수(argument)는 무엇일까요?

나머지 매개변수를 사용하면 함수가 1,2개가 아닌 많은 개수의 인수를 배열로 받아들일 수 있습니다. '...' 구문으로 표시되며 함수가 하나 이상의 인수를 받아들일 수 있음을 나타냅니다.

function add(...values: number[]) { //...values는 숫자로 이루어지 배열이다
  let sum = 0;
  values.forEach(val => sum += val);
  return sum;
}
const sum = add(5, 10, 15, 20);
console.log(sum);  // 50

이와 다른 방식으로 나머지 인수(rest argument)를 사용하면 함수에게 배열 내부의 다양한 인수로 제공할 수 있습니다.

const first = [1, 2, 3];
const second = [4, 5, 6];

first.push(...second);
console.log(first);  // [1, 2, 3, 4, 5, 6] 

15. 매개변수 구조분해(parameter destructuring)란 무엇일까요?

매개변수 분해는 함수를 하나 이상의 지역 변수에 인수로 제공된 객채를 구조분해 할 수 있게 합니다.

function multiply({ a, b, c }: { a: number; b: number; c: number }) {
	console.log(a * b * c);
}

multiply({ a: 1, b: 2, c: 3 });

// 위의 코드를 interface나 type을 통해서 간단하게 작성할 수 있습니다.
type ABC = { a: number; b: number; c: number };

function multiply({ a, b, c }: ABC) {
	console.log(a * b * c);
}

multiply({ a: 1, b: 2, c: 3 });

16. TypeScript의 선택적 매개변수(optional parameters) 문법이 뭘까요?

함수는 매개변수에 '?'를 접미사로 붙여 하나 이상의 매개변수를 선택 사항으로 표시할 수 있습니다.

function greet(name: string, greeting?: string) {
if (!greeting)
  greeting = "Hello";

console.log(`${greeting}, ${name}`);
}

greet("John", "Hi");  // Hi, John
greet("Mary", "Hola");  // Hola, Mary
greet("Jane");  // Hello, Jane

7. TypeScript에서 객체를 어떻게 생성할까요?

객체는 사전(dictionary)과 같이 작동하며 key 및 value들의 모음입니다. key는 고유해야 합니다. 배열과 유사하며 연관(유사) 배열이라고도 합니다. 배열은 숫자(0,1, ..)를 사용하여 값을 인덱싱하는 반면 객체는 다른 type을 key로 사용할 수 있습니다.

TypeScript에서 객체는 속성이 있는 모든 값을 참조합니다. property와 해당 type을 나열하기만 하면 정의할 수 있습니다.

let pt: { x: number; y: number } = {
  x: 10,
  y: 20
};

8. TypeScript에서 선택적 속성( optional properties)을 지정하려면 어떻게 해야할까요?

객체 유형은 속성 이름 뒤에 '?'를 추가하여 선택적 속성(optional properties)을 가질 수 있습니다.

let pt: { x: number; y: number; z?: number } = {
  x: 10,
  y: 20
};
console.log(pt);

위의 코드에서 'z' 속성은 선택적 속성(optional properties)으로 표시되어 있으므로 초기화 중에 제공하지 않아도 컴파일 과정에서 문제가 없습니다.


9. null의 개념과 TypeScript에서의 사용예시를 설명해주세요.

프로그래밍에서 null 값은 값이 없음을 나타냅니다. null 변수는 어떤 객체도 가리키지(참조하지) 않습니다. 그렇기 때문에 변수의 속성에 액세스하거나 해당 메서드를 호출할 수 없습니다.

TypeScript에서 null 값은 'null' 키워드로 표시됩니다.

function greet(name: string | null) {
  // 두가지 경우 모두 내부에서 처리해준다.
  if (name === null) {
    console.log("Name is not provided");
  } else {
    console.log("Good morning, " + name.toUpperCase());
  }
}

var foo = null;
greet(foo); // "Name is not provided"

foo = "Anders";
greet(foo);  // "Good morning, ANDERS"

10. TypeScript에서 undefined가 뭘까요?

변수가 초기화 없이 선언되면 undefined가 할당됩니다. undefined 자체로는 별로 유용하지 않습니다. undefined와 다르게 null은 변수에 할당되었지만 값이 없음을 나타냅니다.

console.log(null == null); // true
console.log(undefined == undefined); // true
console.log(null == undefined); // true, with type-conversion
console.log(null === undefined); // false, without type-conversion
console.log(0 == undefined); // false
console.log('' == undefined); // false
console.log(false == undefined); // false
profile
느리지만 꾸준하게 💪🏻

0개의 댓글