function parseYAML(yaml: string): any {
// ...
}
interface Book {
name: string;
author: string;
}
const book = parseYAML(`
name: Jane Eyre
author: Charlotte Brontë
`);
alert(book.title); // No error, alerts "undefined" at runtime
book('read'); // No error, throws "TypeError: book is not a
// function" at runtime
반환을 any로 하게되면, 작성중에는 오류가 발생하지 않고 런타임에서 오류가 발생합니다. 그리고 사용하는 곳마다 오류가 발생하게 됩니다.
interface Book {
name: string;
author: string;
}
function safeParseYAML(yaml: string): unknown {
return parseYAML(yaml);
}
const book = safeParseYAML(`
name: The Tenant of Wildfell Hall
author: Anne Brontë
`);
alert(book.title);
// ~~~~ Object is of type 'unknown'
book("read");
// ~~~~~~~~~~ Object is of type 'unknown'
unknown 타입을 반환하게 하면 오류를 발생시키고 더 안전하게됩니다.
any
- 어떠한 타입이든 any 타입에 할당 가능하다.
- any 타입은 어떠한 타입으로도 할당 가능하다.
unknown
- 어떠한 타입이든 unknown 타입에 할당 가능하다.
- unknown 타입은 어떠한 타입으로도 할당 가능하지 않다.
never
- 어떠한 타입이든 never 타입에 할당 가능하지 않다.
- never 타입은 어떠한 타입으로도 할당 가능하다.
function parseYAML(yaml: string): any {
// ...
}
interface Book {
name: string;
author: string;
}
function safeParseYAML(yaml: string): unknown {
return parseYAML(yaml);
}
interface Geometry {}
function isBook(val: unknown): val is Book {
return (
typeof(val) === 'object' && val !== null &&
'name' in val && 'author' in val
);
}
function processValue(val: unknown) {
if (isBook(val)) {
val; // Type is Book
}
}
위의 코드처럼 타입 가드를 사용하여 unknown에서 원하는 타입으로 변환할 수 있습니다.
function parseYAML(yaml: string): any {
// ...
}
interface Foo { foo: string }
interface Bar { bar: string }
declare const foo: Foo;
let barAny = foo as any as Bar;
let barUnk = foo as unknown as Bar;
위의 이중 단언문은 기능적으로 동일합니다. 하지만 나중에 두개의 단언문을 분이하는 리팩터링을 한다면 unknown 형태가 더 안전합니다.
{}타입은 null과 undefined 를 제외한 모든 값을 포함합니다.
object 타입은 모든 비기본형(non-primitive) 타입으로 이루어집니다. 여기에는 true 또는 12 또는 "foo"가 포함되지 않지만 객체과 배열은 포함됩니다.
몽키패치란(Monkey patch)
몽키패치는 원래 소스코드를 변경하지 않고 실행 시 코드 기본 동작을 추가, 변경 또는 억제하는 기술이다. 쉽게 말해 어떤 기능을 위해 이미 있던 코드에 삽입하는 것이다.
interface의 특수 기능 중 하나인 보강을 사용(아이템 13 보강 참조)
export {};
declare global {
interface Document {
/** Genus or species of monkey patch */
monkey: string;
}
}
document.monkey = 'Tamarin'; // OK
더 구체적인 타입 단언문을 사용
interface MonkeyDocument extends Document {
/** Genus or species of monkey patch */
monkey: string;
}
(document as MonkeyDocument).monkey = 'Macaque';
<이펙티브 타입스크립트> (댄 밴더캅 지음, 장원호 옮김, 인사이트, 2021)