러닝 타입스크립트 7~9장

:D ·2023년 4월 5일
0
post-thumbnail

7장

p.135

readonly 인터페이스 멤버는 코드 영역에서 객체를 의도하지 않게 수정하는 것을 막는 편리한 방법이나 readonly는 타입 시스템 구성 요소 일 뿐 컴파일된 자바스크립트 출력 코드에는 존재하지 않는다. readonly는 단지 개발 중에 그 속성이 수정되지 못하게 보호하는 역할을 한다.

p.145

파생 인터페이스는 다른 타입으로 속성을 다시 선언해 기본 인터페이스의 속성을 재정의하거나 대체할 수 있다. 속성을 재선언 하는 대부분의 파생 인터페이스는 해당 속성을 유니언 타입의 더 구체적인 하위 집합으로 만들거나 속성을 기본 인터페이스의 타입에서 확장된 타입으로 만들기 위해 사용한다.

예를 들어, WithNonNullableName는 null이 허용되지 않게 재설정 되고, withNumericNamenumber | stringstring | null에 할당할 수 없기 때문에 에러가 난다.

interface WithNullableName {
	name: string | null;
}

interface WithNonNullableName extends WithNullableName {
	name: string;
}

interface withNumericName extends WithNullableName {
	name: number | string; // error
}

8장

-없음-

9장

p. 180

unknown 타입은 any 타입의 값보다 훨씬 제한적으로 취급한다.

// 타입 오류 없음
function greetComedian(name: any){
	console.log(`Annoucing ${name.toUpperCase()}!`);
}

// 타입 오류 있음 
// unknown 타입인 name에 접근할 수 있는 유일한 방법은 instanceof나 typeof 또는 타입 어셔선을 이용해야한다.
function greetComedian(name: unknown){
	console.log(`Annoucing ${name.toUpperCase()}!`);
}

가능하면 any보다는 unknown을 쓰자

p. 183

타입 가드를 정의하기 위해서는 반환 타입이 타입 서술어인 함수를 정의해야 한다.

interface Comedian {
	funny: boolean;
}

interface StandupComedian extends Comedian {
	routine: string;
}

function isStandupComedian(value: Comedian): value is StandupComedian {
	return 'routine' in value;
}

p.185~188
더 설명을 잘 한 자료가 있어 참고.

  • keyof : 객체 형태의 타입을, 따로 속성들만 뽑아 모아 유니온 타입으로 만들어주는 연산자
    type Type = {
       name: string;
       age: number;
       married: boolean;
    }
    
    type Union = keyof Type;
    // type Union = name | age | married
    
    const a:Union = 'name';
    const b:Union = 'age';
    const c:Union = 'married';
  • typeof : 객체 데이터를 객체 타입으로 변환해주는 연산자, 객체에 쓰인 타입 구조를 그대로 가져와 독립된 타입으로 만들어 사용하고 싶다면, 앞에 typeof 키워드를 명시해주면 해당 객체를 구성하는 타입 구조를 가져와 사용할 수 있다.
    const obj = {
       red: 'apple',
       yellow: 'banana',
       green: 'cucumber',
    };
    
    // 위의 객체를 타입으로 변환하여 사용하고 싶을때
    type Fruit = typeof obj;
    
    /*
    type Fruit = {
        red: string;
        yellow: string;
        green: string;
    }
    */
    
    let obj2: Fruit = {
       red: 'pepper',
       yellow: 'orange',
       green: 'pinnut',
    };
  • keyof typeof
    const obj = { red: 'apple', yellow: 'banana', green: 'cucumber' } as const; // 상수 타입을 구성하기 위해서는 타입 단언을 해준다.
    
    // 위의 객체에서 red, yellow, green 부분만 꺼내와 타입으로서 사용하고 싶을떄
    type Color = keyof typeof obj; // 객체의 key들만 가져와 상수 타입으로
    
    let ob2: Color = 'red';
    let ob3: Color = 'yellow';
    let ob4: Color = 'green';

p.190

타입 어셔선을 사용하지 않는 것이 좋지만 필요한 경우가 있다.

1. Error

try {
} catch(error) {
	console.log((error as Error).message)
}

// 더 안전한 방법
try {
} catch(error) {
	console.log((error instanceof Error ? error.message : error)
}

2. non-null 어서션

null 또는 undefined를 포함할 수 있는 변수에서 nullundefined를 제거할 때 사용

let maybeDate = Math.random() > 0.5 ? undefined : new Date()

maybeDate! // 타입이 Date라고 간주됨

References

profile
강지영입니...🐿️

0개의 댓글