TypeScript) Basic-1

이해원·2022년 4월 11일

공부중

목록 보기
1/2

type)
원시형 : numbers, string,boolean,(null,undefined)
좀더 복잡한 types : arrays,objects
Function types, parameters

let variable : type;

variable = type에 맞는 형태

예)

//Primitives

let age: number;

age = 12;

let userName: string;

userName = "momo";

let isInstructor: boolean;

isInstructor = true;

//더 복잡한 형태
배열 
let hobbies :string[];
hobbies=['soccer','basketball'];

객체
let person:{
    name:string;
    age:number;
};
person={
    name:'haewon',
    age:29
}
// person={
//     isEmployee :true;
// }

//객체를 배열안에 넣기(combining different types)

let people:{
    name:string;
    age:number;
}[];


//Type inference

let course = "Typescript basic";

course = 3579; <- error 발생!

type inference
type을 우리가 따로 명시하지 않더라도 Typescript가 알아서 해석해서 type을 정한다

이런식으로
let course : string = 'Typescript basic';

따로 안적어줘도되서 code를 덜 적을수 있다는 장점

그러므로 couse = 3579; 에서 number 가 들어온다면 위에서 type이 string으로 정해졌기때문에 에러가 난다

하지만 만약 string, number 둘다 사용하고 싶다면?

예를들어 course 를 string 으로 제목으로 저장하거나 number로 course번호를 저장할수도 있다
바로 이럴때는 Union Type을 사용한다

여러가지 type 사용할때 union type 사용하기 : | (pipe symbol)

let course: string | number = "Typescript basic";

pipe 를 써서 옆에 붙이고 싶은만큼 type을 붙일수 있다.

type inference 말고도 어디에나 union type 사용 가능하다

let Username :string | string[ ];

profile
미어캣입니당

0개의 댓글