220814 types of typescript

hjnoh·2022년 8월 14일
0

TIL

목록 보기
2/2

basic

let a : number = 1
let b : string = "hello"
let c : boolean = true

let aa : number[] = [1,2]
let bb : string[] = ["hello", "world"]
let cc : boolean[] = [true, false]

types for object fields

?는 해당 필드가 없을 수도 있다는 것을 명시한다.

const player : {
    name: string,
    age?: number
} = {
    name: "hjnoh"
}

🛑 Alias : make a type

type Name = string
type Person = {
    name: Name,
    age?: number,
    email?: string
}

const personMe : Person = {
    name: "hjnoh"
}

types for function arguments and returns

type Player = {
    name: string,
    age?: number,
}

function playerMaker(name: string) : Player {
	return {name}
}

const playerMe = playerMaker("hjnoh")
playerMe.age = 3 // this works!

making types to readonly

type Player = {
    readonly name: string,
    age?: number,
}

const playerMaker = (name: string) : Player => ({name})

const playerMe = playerMaker("hjnoh")
playerMe.age = 3 // this works!
playerMe.name = "hjnohh" // this not works

const numbers : number[] = [1,2,3,4]
numbers.push(5) // this not works

Tuples

const player: [string, number, boolean] = ["hjnoh", 1, true]
const playerRO: readonly [string, number, boolean] = ["hjnoh", 1, true]

Unknown

let a:unknown;
let b = a + 1 // Error

if(typeof a === 'unknown'){
	let b = a + 1 // this works
}

void, never

function hello() { // 아무것도 지정해주지 않으면 자동으로 void타입을 리턴함.
	console.log("x")
}

function hello() : never { // 리턴이 전혀 필요없는 경우 never 사용
	throw new Error("xxx")
}

function hello(name: string|number){
	name + 1 // this not works
	if (typeof name === "string"){
		name
	} else if (typeof name === "number"){
		name
	} else { // this should never run if the type of name is correct.
		name
	}
}

0개의 댓글