May 31, 2021
const documents: IDocument[] = []
const documents: Array<IDocument> = [] // 제네릭 배열 타입const getDocument = (documentInfo: { title: string }) => {}
const myObj = { title: 'doc1', likes: 1 }
getDocument(myObj)컴파일러가 interface에 정의된 타입만 확인하기 때문에 최소한의 프로퍼티가 있는지와 타입만 검사하게 된다. 따라서 getDocument가 전달해주는 인자에 likes라는 property가 있지만 컴파일러는 최소한의 타입 검사만 하기 때문에 위 예제의 경우 정상적으로 컴파일 된다.
interface IDocument {
title?: string
likes?: number
}
function createDocument (config: IDocument): { title: string; likes: number } {}
createDocument({ titles: 'hahaha', likes: 4 }) //typescript에서는 최소한의 프로퍼티 검사만 하고, IDocument의 경우 optional property를 사용하고 있기 때문에 위 코드는 에러가 나지 않을거 같지만, error가 난다. (createDocument의 인자로 넘겨주는 object에서 title은 없고, likes만 있는 상황)
그 이유는 객체 리터럴의 경우 다른 함수의 인자나 변수에 할당될 때, Excess Property Checks가 실행되기 때문이다. 객체 리터럴이 대상 타입(IDocument)에 맞지 않는 프로퍼티를 가지고 있다면 에러를 출력한다.
const obj = {
title: 'doc1',
}
let key = 'title'
console.log(obj[key]) // errorString Literal 타입을 사용해야 하는 곳에 string type을 넣게 되면 error가 난다. string literal type은 string 보다 좀 더 narrow 한 타입으로 특정 문자열로 type을 체크한다.
const key = 'title' // String Literal type (string 이자 'title' 문자열이여야만 함)