Study/24-2 GDSC Regular Session

TypeScript: 타입에 엄격한 자바스크립트

selfdevelop 2024. 11. 22. 20:38

JS: 동적 타입핑. 따라서 런타임 에러(실행시점)가 발생.

TS: 타입 지정(추론). 런타임 에러 방지.

*변수의 경우 타입을 명시적으로 지정하지 않아도 초깃값을 통해 TS가 타입을 추론하여 지정할 수 있다.

 

변수 타입 표기

let myName: string = "Alice";
let myName = "Alice";
// 타입 표기가 필요하지 않습니다. 'myName'은 'string' 타입으로 추론됩니다.

 

함수 타입 표기 - 매개변수, 반환 타입 

function greet(name: string) {
  console.log("Hello, " + name.toUpperCase() + "!!");
}
function getFavoriteNumber(): number {
  return 26;
}

 

*화살표 함수, 익명 함수에도 추론을 통한 타입 지정이 적용된다.

 

객체 타입 표기

 

옵셔널 프로퍼티: 선택적인 타입. 

+ 값이 존재하지 않는 경우 undefined 값을 얻게 됩니다. 이 때문에 옵셔널 프로퍼티를 읽었을 때, 해당 값을 사용하기에 앞서 undefined인지 여부를 확인해야 합니다.

function printName(obj: { first: string; last?: string }) {
  if (obj.last !== undefined) {
    // OK
    console.log(obj.last.toUpperCase());
  }
}

// 둘 다 OK
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });

 


Narrowing: 타입 좁히기.

Narrowing 판정 문법

- typeof 변수

function 함수(x: number | string) {
  if (typeof x === 'string') {
    return x + '1'
  } else {
    return x + 1
  }
}

 

- 속성 in 객체

function check2(animal: Fish | Bird) {
  if ('swim' in animal) { // swim이라는 속성이 animal이라는 오브젝트에 있는지
    animal.swim
  }
}

 

 

- 객체 instanceof 부모 class

let 날짜 = new Date()
if (날짜 instanceof Date) { // 왼쪽 오브젝트(=날짜)가 오른쪽에 있는 class(=Date)의 자식인지
  console.log('today')
}

*const message = "hello" 

String이 아닌 문자열 리터럴 자체를 타입으로 지정. 따라서 String 객체의 내장 함수를 사용할 수 없음.

const message = "hello!";
 
message();
This expression is not callable.
  Type 'String' has no call signatures.

Truthiness narrowing(유효한 값인가?)

[TS가 false로 판단하는 값]
0
NaN
"" (the empty string)
0n (the bigint version of zero)
null
undefined

function init(){

return "hello";

}

const a = init()

//함수의 결과값이 담긴다. a = hello

const b = init

//함수 자체가 담긴다. b = fuction init() { ...

function flipCoin() {
  // 본래 의도는 Math.random()
  return Math.random < 0.5;
Operator '<' cannot be applied to types '() => number' and 'number'.
}

npm run dev 을 실행할 때, 컴파일이 된다

 


any: 어떤 타입도 허용한다. 무의미.