본문 바로가기

개발/TS

[TS] TS Doc Handbook 1회독 - 4

Object Types

익명 또는 interface와 type을 사용해서 네이밍을 해서 타입으로 사용할 수 있다.

 

정리 노트

 

property modifiers

optional properties

strictNullChecks 옵션을 사용하면 옵셔널 속성의 경우 undefined가 될 수 있음을 알려준다.

 

주의 사항

// 아래 코드와 같이 destructuring pattern을 사용한 경우에는
// 내부에 따로 type을 작성할 수 없다.
// 왜냐하면 이미 js에서 사용되는 문법이니까
function draw({ shape: Shape, xPos: number = 100 /*...*/ }) {
  render(shape);
  // Cannot find name 'shape'. Did you mean 'Shape'?
  render(xPos);
  // Cannot find name 'xPos'.
}

// 아래와 같이 새로운 타입을 정의해 사용해야 한다.
function paintShape({ shape, xPos = 0, yPos = 0 }: PaintOptions) {
  console.log("x coordinate at", xPos);
                                  
(parameter) xPos: number
  console.log("y coordinate at", yPos);
                                  
(parameter) yPos: number
  // ...
}

 

readonly properties

readonly 키워드를 사용하면 runtime에서 어떤 동작을 해도 변경할 수 없다. 속성 내부의 값을 변경하는 것은 어쩔 수 없지만, 자기자신을 바꾸는 것은 불가능하다. 마치 const로 선언된 것과 비슷하다.

interface SomeType {
  readonly prop: string;
}

type Some = {
  readonly prop:string;
}

 

mapping modifiers를 사용하면 readonly 속성을 지울 수 있다.

interface Person {
  name: string;
  age: number;
}
 
interface ReadonlyPerson {
  readonly name: string;
  readonly age: number;
}
 
let writablePerson: Person = {
  name: "Person McPersonface",
  age: 42,
};
 
// works
let readonlyPerson: ReadonlyPerson = writablePerson;
 
console.log(readonlyPerson.age); // prints '42'
writablePerson.age++;
console.log(readonlyPerson.age); // prints '43'

 

Index Signature

interface StringArray {
  [index: number]: string;
}

 

Excess Property Checks(초과 속성 검사)

index signature를 사용해 추가 속성이 존재할 가능성을 넓힐 수 있다.

interface SquareConfig {
  color?: string;
  width?: number;
  [propName: string]: unknown;
}

 

어려운 부분...

 

Extending Types

extends 키워드를 사용해 여러 interface의 관계를 나타내고, 타입을 확장시킬 수 있다.

 

InterSection Types

& 연산자를 사용해 타입을 확장하는 방법

 

Interface Extension vs Intersection

참고

무료 사이트 모음 2021, 자라는 것을 잘하는 개발, 2025.02.06

https://www.typescriptlang.org/ko/docs/handbook/typescript-from-scratch.html, 2025.02.06

https://opentutorials.org/course/5080, 생활코딩, 2025.02.06

'개발 > TS' 카테고리의 다른 글

[TS] TS Doc Handbook 1회독 - 6  (0) 2025.06.16
[TS] TS Doc Handbook 1회독 - 5  (1) 2025.06.13
[TS] TS Doc Handbook 1회독 - 3  (0) 2025.02.28
[TS] TS Doc Handbook 1회독 - 2  (0) 2025.02.26
[TS] TS Doc Handbook 1회독 - 1  (0) 2025.02.06