: 반복을 줄임으로써 코드 덜 적어도되고, 코드를 더 정확하고 유지하기 쉽게 만들어준다
JS value가 아니라 type definition이다
type(alias) 을 직접 만들어준다.
type Person = {
name: string;
age: number;
};
추후 이 object type이 쓰인곳마다 반복해서 alias를 대신 쓸수있다
let person : {
name: string;
age: number;
}
let people : {
name: string;
age: number;
}[]
->
let person : Person;
let people : Person[]
//Functions & types
function add(a :number ,b:number){
return a+b;
}
function 의 parameter에 type을 적어주는데 이 함수에서 inferred type이 쓰인곳이있다
바로 a+b
이 함수에서는 Typescript가 returned value에 type을 명시하고 있다.
왜냐? 우리는 이미 parameter에 들어갈 값이 number라고 말해주었기 때문에 따로 이렇게
function add(a :number ,b:number) : number{
return a+b;
}
return type 이 number라고 명시해 주지 않아도 return value에는 number밖에 나오지 못할것이다.
물론 여기에는 이렇게 ((a:number,b:number):number | string | boolean) 따로 union type으로 적어줄수있지만 이미 Typescript가 return type을 정한 경우 따로 이유가 있지않는한 이렇게 적으면 안된다.
function printOurput(value: any) {
console.log(value);
}
이것은 오직 log로 value를 찍어볼때만 사용하는 type이다.
이 function에서 중요한 점은 return 값이 없는것인데 그래서 'viod'라고 불리는 특별한 return type을 가진다
void는 기본적으로 null & undefined 과 비교되는데 void는 오직 function과 같이 사용할때만 쓰인다. 그말뜻은 함께 쓰인 function은 절대 return 값을 가지지 않는다는 것을 의미한다.
그래서 return value를 가지기 위해서는 undefined 를사용해야한다
function insertAtBeginning(array: any[], value: any) {
const newArray = [value, ...array];
return newArray;
}
const demoArray = [1, 2, 3];
const updatedArray = insertAtBeginning(demoArray, -1); //[-1,1,2,3]
updatedArray[0].split('');
여기서는 typescript가 updatedArray의 처음에 추가된 -1이 number인지 모른다. any라고 써놔도 개발자들은 알지만 typescript는 해석하지 못한다.
updatedArray에 string일때만 쓸수있는 split 써도 에러가 안나는 대신 number를 split 할수 없으니 runtime 에러가 발생한다.
그래서 이것을 Generic type 으로 변경시
function insertAtBeginning<T>(array: T[], value: T) {
const newArray = [value, ...array];
return newArray;
}
const demoArray = [1, 2, 3];
const updatedArray = insertAtBeginning(demoArray, -1); //[-1,1,2,3]
const stringArray = insertAtBeginning(["a", "b", "c"], "d");
//updatedArray[0].split(''); <- error!
이제는 array에 사용된 type과 value의 type이 동일하다고 주었기때문에 typescipt가 이를 해석하여 밑에서 updatedArray를 split 하려하니 updatedArray 는 number로 이루어져 있기때문에 split 할수없다고 오류가 난다!
어떠한 type과도 쓸수있다.한번 그 function에 type이 정해지고 실행되고 나면 그 type은 변경되지않으며 알려진다.