Programing Language/JS & TS

TypeScript 자료형

칼쵸쵸 2023. 3. 23. 18:36

1.  Primitive typestring,  number,  boolean

숫자는 모두 number으로 사용 정수, 소수 간 연산 시에도 같은 자료형이기 때문에 형변환 필요 없음

primitive type도 객체로 취급하나 number는 string으로 자동 형변환 되지 않음

boolean은 스트링과 결합시 자동형 변환됨

number + string 불가

number + boolean 불가

string + boolean 가능

const t = {
    a1 : "1",
    a2 : 1,
    a3 : 0.1,
    a4 : true
}

console.log(t.a2+t.a3) // 1.1
console.log(t.a1+t.a2.toString()) // "11"
console.log(t.a1+t.a3.toString()) //"1.01"
console.log(t.a1+t.a4) //"1true"

//console.log(t.a2+t.a4) => 불가
//console.log(t.a1+t.a2) => 불가

* 변수 선언 시에

let a : string = "1" 과 같이 유형을 정해놓을 수 있음

2.  Array

array 안에 다른 자료형이 함께 들어갈 수 있음

const arr = ["1",2,3,4]
for(let i of arr)
{
    console.log(i)
}
//"1",2,3,4

for(let i in arr)
{
    console.log(i)
}
//"0","1","2","3"

* for문의 경우 of를 사용하면 array안의 값을 반환하고 in을 사용하면 index를 반환함

 

3.  any

정해지지 않은 형태를 의미함

선언되지 않은 함수나 사용할 수 없는 코드를 사용하더라도 코드레벨에서 에러로 처리하지 않음

실제로 실행 시에는 에러로 처리함

let a1:any = 1
a1.foo(); // 코드상에서는 에러가 아니나 런타임에서 에러 발생

function a(t:any)
{
    return t.toString();
}

let t = a(1)
console.log(t) // "1"

 

4. 익명 함수

기존의 함수형 프로그래밍처럼 함수를 변수에 주입할 수 있음

let f = function()
{
    return 1
}

let f2 = ()=>1

console.log(f())
console.log(f2())

 

5. Object type

객체의 각 속성의 형태를 정의해 놓고 사용할 수 있음

자바의 데이터 타입 객체를 생성하는 것과 같음

let pt: { x: number; y: string } = { x: 3, y: "4" }

console.log(pt.x)//3
console.log(pt.y)//"4"

 

type of를 사용해서 기존 만들어진 객체의 형태를 따르는 파라미터를 만들 수 있다.

let pt: { x: number; y: string } = { x: 3, y: "4" }

function f(a :typeof pt)
{
    return pt.x.toString()+pt.y;
}

console.log(f(pt)) //"34"

 

만약 null을 허용하는 속성을 만들고 싶다면 파라미터 뒤에?를 붙여준다.

function f ( pt :{ x: number; y?: string })
{
    if(pt.y==undefined)
    {
        console.log("y is undefined")
    }
    return pt.x.toString()+pt.y;
}

console.log(f({x:1})) //"y is undefined" , "1undefined"

 

6. Union Type

 

지정된 여러 개의 형태를 사용 가능한 타입

단 기본함수 (tostring, touppercase)를 사용할 시에는 해당 형태의 변수를 사용할 시에는 지정된 형태의 모든 형태들이 사용가능 해야 사용할 수 있음

직접 사용하는 함수에서 파라미터로 받을 시에는 typeof 연산으로 분기 처리 해서 사용

 

function f ( x: number | string )
{
    //x.toUppercase() -> x가 number가 될수 있어서 불가

    if(typeof x == "string")
    {
        console.log("x is string")
    }
    else
    {
        console.log("x is not string")
    }
}

f("1") //"x is string" 
f(1) //"x is not string"

 

* type 대신에 union에 리터럴값을 넣는 다면 해당 값만을 가지게 될 수 있다.

function f ( x: number | "1" |true)
{
    //x.toUppercase() -> x가 number가 될수 있어서 불가

    if(typeof x == "string")
    {
        console.log("x is string")
    }
    else
    {
        console.log("x is not string")
    }
}

f("1") //"x is string" 
f(1) //"x is not string"
//f("2") => 컴파일 에러
f(true)
//f(false) => 컴파일 에러

7. 인터페이스

object type 선언과 비슷하나 인터페이스로서의 특징을 가지고 있음

필드값에 대한 overwrite가 가능하며 해당 인터페이스를 상속함으로써 새로운 필드를 추가할 수 있음

interface Animal {
  name: string
}

interface Bear extends Animal {
  honey?: boolean
}

const bear :Bear = {name:"teddy",honey:true}
console.log(bear.name)
console.log(bear.honey)

인터페이스도 마찬가지로 특정 속성에는 Null을 허용할 수 있다.