개요Optional Propertiesreadonly 프로퍼티Extending typesIntersection TypesGeneric Object TypesArrayReadonlyArrayTuple TypesIndex signature
개요
- 오브젝트의 타입을 나타내기 위해서
interface
혹은type alias
를 사용할 수 있음
interface Person { name: string; age: number; } function greet(person: Person) { return "Hello " + person.name; } type Person = { name: string; age: number; }; function greet(person: Person) { return "Hello " + person.name; }
Optional Properties
interface PaintOptions { shape: Shape; xPos?: number; yPos?: number; } 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 // ... }
- 여기서 주의할 점은 구조 할당에서
type annotation
을 바꿀 수는 없다는 점임. 왜냐하면 그렇게 할당하는 문법이 이미 자바스크립트에서 다른 기능으로 정의되어 있기 때문
function draw({ shape: Shape, xPos: number = 100 /*...*/ }) { render(shape); Cannot find name 'shape'. Did you mean 'Shape'? render(xPos); Cannot find name 'xPos'.
shape: Shape
의 의미는shape
프로퍼티를 지역 변수Shape
로 다시 정의해라 라는 의미
readonly
프로퍼티
interface SomeType { readonly prop: string; } function doSomething(obj: SomeType) { // We can read from 'obj.prop'. console.log(`prop has the value '${obj.prop}'.`); // But we can't re-assign it. obj.prop = "hello"; Cannot assign to 'prop' because it is a read-only property. }
- readonly 를 사용한다고 해서 값이 immutable 하다는 의미는 아님
- property 자체 값이 다시 쓰여질 수 없다는 의미 ⇒ Java
final
과 동일
Extending types
interface BasicAddress { name?: string; street: string; city: string; country: string; postalCode: string; } interface AddressWithUnit extends BasicAddress { unit: string; }
interface Colorful { color: string; } interface Circle { radius: number; } interface ColorfulCircle extends Colorful, Circle {} const cc: ColorfulCircle = { color: "red", radius: 42, };
Intersection Types
interface Colorful { color: string; } interface Circle { radius: number; } type ColorfulCircle = Colorful & Circle;
- 두 개의 interface를 결합시키고 싶을 때
intersection type
을 사용함
Generic Object Types
interface Box<Type> { contents: Type; }
Array
ReadonlyArray
Tuple Types
type StringNumberPair = [string, number];
Tuple
타입은Array
타입과 비슷한 형태로 몇개의 요소가 배열에 포함되어 있는지 알고, 특정 위치에 어떤 타입이 위치하고 있는지를 알 수 있는 type 임
Index signature
[ TS Docs ] Index Signatures
interface StringArray { [index: number]: string; } const myArray: StringArray = getStringArray(); const secondItem = myArray[1];
- object 의 property 이름을 다 모르지만 그 타입은 알 때, index signature를 이용해서 가능한 값의 타입을 서술할 수 있음
- StringArray 인터페이스는 number 타입을 키로 가지면서 string 타입을 value로 갖는다는 것을 명시한 것