▶ 함수의 인수type 설정하는 법
type Player = {
name:string,
age?:number
}
function playerMaker(name:string) : Player {
return (
name:name
)
}
const playerMaker = (name:string) : Player => {(name:name)}
▶ readonly 속성 : 요소들을 '읽기전용'으로 설정
type Player = {
readonly name:name
age?:age
}
const nico = playeMaker("yu")
nico.name="alice" // 이렇게되면 에러발생!
const numbers:readonly number[] = [1,2,3,4]
numbers.push(1) // 에러발생!
▶Tuple : array를 생성할 때, 특정 위치에 특정타입이 존재해야할 경우
// ["yu", 12, false]
// 차례로 string number boolean type의 배열이 필요한 상항
const player:[string,number,boolean]=["yu",1,true]
// 이렇게 설정하면 특정위치에 특정타입이 설정되어짐!
const player:readonly [string,number,boolean]=["yu",1,true]
// readonly 옵션도 당연히 추가 가능
▶ any : 비어있는 값들은 기본적으로 any type
let a = [] // any[]타입을 갖게되어짐
any는 typescript의 장점인 type보호로부터 빠져나오고 싶을때 사용 -> 어떤 타입이든지 될 수 있음
any type을 사용하게되면 javascript처럼 작동하기때문에 typescript의 장점이 사라짐
※ 웬만해서는 사용X
가끔 사용해야할때가 있는데 그럴때 사용!
▶ unknown : Typescript의 핵심은 TypeChecker와 소통하는 것!
어떤 타입인지 모르는 type과 소통해야할때 사용하는 Type
//API를 통하거나 다른 외부 resource에서 값을 받아오는 상활일 경우라고 가정
let a : unknown;
// a의 타입이 무엇인지 모르기때문에 if문을 통해 a가 number일 경우만 아래와 같이 실행 if문 없을 경우 에러 발생
if(typeof a === 'number'){
let b = a+1
}
// 같은 이유로 string인지 검사
else if (type of a=== 'string'){
let b = a.toUpperCase();
}
▶ void : 아무것도 return하지 않는 함수에 사용
// 이와 같은 함수의 type은 자동으로 void
// TypeScript가 return값이 없는 것을 자동으로 파악해서 void type 설정
function hello(){
console.log("hi")
}
▶ never : 함수가 절대 return하지 않을 경우 사용
return 하지 않고 error를 발생시킬 수 있는 함수의 type으로 사용됨
function hello : never{
throw new Error("xxx")
}
function hello(name:string|number){
if(typeof name === "string"){
// name의 type이 string일 경우
}
else if(typeof name === "number"){
// name의 type이 number일 경우
}
else{
name
// 이때 name의 type은 never
// 위 조건에서 name이 string이거나 number일 것이라고 TypeScript에 지정했기 때문에
// 이 코드는 절대 싱행되면 안됨 따라서 name의 type이 never로 설정되어짐
}
'Web_Study > TypeScript' 카테고리의 다른 글
TypeScript_6:Generic_2 (0) | 2022.06.02 |
---|---|
TypeScript_5:Polymorphism & Generic (0) | 2022.05.31 |
TypeScript_4:CallSignature & Overloading (0) | 2022.05.26 |
TypeScript_2:Types (0) | 2022.05.22 |
TypeScript_1 : Why use TypeScript? (0) | 2022.05.22 |