[Typescript] 기본 타입 훑어보기

rondido·2023년 2월 22일
0

Typescript

목록 보기
1/6
post-thumbnail

기본 타입 훑어보기

Primitive(원시값)

  • 불변
  • 객체가 아닌 값
const str:string = "String"
const num:number = 123
const bool:boolean = true

//타입 유도하기
const str:'string'= "String"
const num:123 = 123
const bool:true = true

//error
const str:'string'= "String1"
const num:123 = 12345
const bool:true = false

//타입 추론
const str= "String"
const num= 123
const bool = true

const big: bigint = 100n;

객체


// any와 다를게 없는 상황
//더 자세히 요사해주어야함 다양한 형태로 만들어 질 수 있기 때문에
const obj: object = {
    str : 'str',
    num :123,
    child:{
        str: 'str',
        num : 123,
    }
}

const obj2: {str:string, num:number, child:{
    str: string,
    num: number

}} = {
    str : 'str',
    num :123,
    child:{
        str:'str',
        num :123,
    }

}

console.log(obj2.str);

함수

  • 반환타입은 타입추론이 잘되는 타입이다.
function func(num:number, str:string):string{
    return num + str
}

func(123,'str');

function func2(num1:number, num2:number):number{
    return num1 + num2
}

func2(123, 123);

function func3(num1:number, num2:string):number{
    return num1 + Number(num2)
}

func3(123, '123');

function func4(num1:number, num2:string):void{
    console.log(num1 + num2)
}

func4(123, '123');

const func5 = (str1:string, str2:string):string =>{
    return str1+ ' ' +str2
}

func5('hello', 'world');

const func6 = (obj:{str1:string, str2: string}) =>{
    return obj.str1 + ' ' + obj.str2
}

func6({str1: 'hello', str2:'world'})

배열

const strArr : string[] = ['str', 'str2', 'str3'];

const strArr2 : Array<string> = ['str', 'str2', 'str3'];
const numArr : Array<number> = [1,2,3];

const boolArr : boolean[] = [false,true,true,false];

// strArr.push(1) //error

// numArr.push('str') // error

boolArr.push(true);

const arr = ['str', 123, false];

리터럴

  • 특정 타입을 가질 수 있는 특정 값을 리터럴 타입이라고 함.
let letString = 'hello'

letString //string

const constString = 'Hello';

constString //Hello

let letNumber = 123

letNumber //number

const constNumber = 123

constNumber //123
  • 위 처럼 나오는 이유는 let은 재할당 할 수 있기 때문

튜플

  • 길이 고정 & 인덱스 타입이 고정
  • 여러 다른 타입으로 이루어진 배열을 안전하게 관리
  • 배열 타입의 길이 조절

const arr1: string[] = ['A','B','C']

const arr1: string[] = ['A','B','C']

const tuple: [number, string] = [1,'A']
const tuple0 : (string | number)[] = [1,'A'] //// (string | number) []; 유니온 타입을 뜻 함.
const tuple2: [number, ...string[]] = [0,'A', 'B'] 

undefind null

const nu: null =null;

const un : undefined = undefined;

console.log( nu == un) //true
console.log( nu === un) //false

function sayHello(word: string){
    if(word === 'world'){
        return 'hello' + word
    }
    return null
} // string || null을 알아서 추론함.. null이 아닌경우는 undefined로 추론

function log(message: string | number){
    console.log(message);
    return undefined;
} //아무것도없다면 void | return undefined

any

  • 모든 값(타입)의 집합
  • 사용자밀자
  • noImplicitAny or stict 옵션 true 권장(tsconfig.json)
//tsconfig에서 Noimplicitany 사용을 권장
// 암시적으로 any를 컴퍼일러가 알아 둘 수 있는 상황을 방지
//js 문법이기 때문에 ts에서 추론할 수 없다.
function func(anyParam: any){
    anyParam.trim()
}

func([1,2,3])

unknown

  • 새로운 최상위 타입
  • any처럼 모든 값을 허용하지만 상대적으로 엄격하다
  • TS에서 unknown으로 추론하는 경우는 없으니 개발자가 직접 명시해야함.
  • assertion 혹은 타입 가드와 함께 사용
  • 직접적으로 unknown이라고 명시해 주지 않으면 ts에서 any로 추론 할 경우가 있다.
function func(x: any){
    let v1:any = x;
    let v2:unknown = x;
    let v3:string = x;
    let v4:boolean = x;
    let v5:number = x;
    let v6:string[] = x;
    let v7:{} = x;

}

let num:unknown = 99; //any로 출론

// typeof 를 사용하여 타입이 맞는지 검증한다(타입가드)
if(typeof num === 'string'){
    num.trim() 
}

// function func(x: unknown){
//     let v1:any = x;
//     let v2:unknown = x;
//     let v3:string = x;
//     let v4:boolean = x;
//     let v5:number = x;
//     let v6:string[] = x;
//     let v7:{} = x;
//     //any와 unknown을 제외 나머지는 에러가 발생
// }

void

  • return을 하지 않으면 undefined를 반환
  • 함수의 반환이 없는 경우를 명시
  • 타입 추론에 위임하자
  • javascript에서는 암시적으로 undefined 반환
  • 그러나 void와 undefined는 typescript에서 같은 것이 아님
function test(): undefined{
    return undefined
}

function test2(): void{

}

function voidFunc(){
    
}// void로 추론하고 있기 때문에 굳이 타입을 명시하지 말고 타입 추론에 맡기자

// 위에 2개의 함수는 같지 않다.
profile
개발 옆차기

0개의 댓글