프로그래밍/타입스크립트

[타입스크립트] 기본자료형에 대해서

znvlcm 2022. 7. 27. 16:48

 

기본자료타입
자료형 변수 초기화 타입확인
불리언 boolean
const bool :boolean = true
typeof(bool) === "boolean";
숫자 number
const num : number =  1
typeof(num) === "number";
문자열 string
const str : string = "str"
typeof(str) === "string";
배열 array
const arr:number[] = [1,2,3,4]  || const arr : Array<number> = [1,2,3,4],
Array.isArray(arr);
튜플 tuple
let tuple : [number, string] = [1, "2"];
 
열거형 enum
enum Color {Red="#FF0000", Green="1", Blue="#0000FF"} ;
 
Any 타입무시
let any_type : any = [1,"2", true];
any_type = "str"
 

 

더보기
const bool:boolean = true
const isBoolean = typeof(bool) === "boolean";



const num:number =  1;
const isNumber = typeof(num) === "number";



const str:string = "str"
const isString = typeof(str) === "string";



const arr:Array<number> = [1,2,3,4]
const isArr = Array.isArray(arr);

 

let tuple : [number, string] = [1, "2"];

 

enum Color {Red="#FF0000", Green="1", Blue="#0000FF"} ;




console.log("typeof bool:",typeof bool)
//typeof True
console.log("*** 대소문자주의 typeof True는 에러 발생 : Error Cannot find name 'True'.")
console.log(`typeof(bool) === "boolean"; => ${isBoolean}`);



console.log("typeof num:",typeof num)
console.log(` typeof(num) === "number"; => ${isNumber}`);

 

console.log("typeof str:",typeof str)
console.log(` typeof(str) === "string"; => ${isString}`);

 

console.log("typeof arr:",typeof arr,"배열도 일종의 오브젝트라 타입오브는 object를 반환")
console.log(`**** 에러 !!!! const isArray = typeof(arr) === "Array"; `);
//const isArray = typeof(arr) === "Array"
console.log(`**** This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Array"' have no overlap.`)
console.log('**** 배열 타입확인은 Array.isArray(arr) 을 이용')
console.log(`Array.isArray(arr) ${isArr}`);



console.log("typeof tuple:",typeof tuple)
console.log("** 튜플은 배열의 길이를 한정하고 특정위치의 타입을 지정할 수 있음")
//tuple = [1,2]
console.log("** tuple: [number, string] = [1,2]은 에러 Type 'number' is not assignable to type 'string'.")



console.log("typeof Color:",typeof Color)



const green = Color.Green;
console.log("green Color.Green:",green,"typeof green",typeof green)

 

let any_type : any = [1,"2", true];
console.log('let any_type : any = [1,"2", true];');
console.log('typeof any_type', typeof any_type)
any_type = "str";
console.log('any_type = "str";');
console.log('typeof any_type', typeof any_type)
 

실행결과

[LOG]: "typeof bool:",  "boolean" 
[LOG]: "*** 대소문자주의 typeof True는 에러 발생 : Error Cannot find name 'True'." 
[LOG]: "typeof(bool) === "boolean"; => true" 
[LOG]: "typeof num:",  "number" 
[LOG]: " typeof(num) === "number"; => true" 
[LOG]: "typeof str:",  "string" 
[LOG]: " typeof(str) === "string"; => true" 
[LOG]: "typeof arr:",  "object",  "배열도 일종의 오브젝트라 타입오브는 object를 반환" 
[LOG]: "**** 에러 !!!! const isArray = typeof(arr) === "Array"; " 
[LOG]: "**** This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Array"' have no overlap." 
[LOG]: "**** 배열 타입확인은 Array.isArray(arr) 을 이용" 
[LOG]: "Array.isArray(arr) true" 
[LOG]: "typeof tuple:",  "object" 
[LOG]: "** 튜플은 배열의 길이를 한정하고 특정위치의 타입을 지정할 수 있음" 
[LOG]: "** tuple: [number, string] = [1,2]은 에러 Type 'number' is not assignable to type 'string'." 
[LOG]: "typeof Color:",  "object" 
[LOG]: "green Color.Green:",  "1",  "typeof green",  "string" 
[LOG]: "let any_type : any = [1,"2", true];" 
[LOG]: "typeof any_type",  "object" 
[LOG]: "any_type = "str";" 
[LOG]: "typeof any_type",  "string"
typeof가 확인가능한 자료형
자료형에 따라 처리가 다를 때 typeof를 활용하는데 
아래와 같은 에러메세지를 볼 수 있으니 주의

This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Array"' have no overlap.

typeof가 체크할 수 있는 자료형은 string, number, binint, boolean, symbol, undefined, objec, function이다. 
배열이나 enum은 object의 일종으로 이런 타입은 typeof로 확인이 불가능함.
*** 배열은 Array.isArray(arr)로 확인할 것 

타입스크립트와 자바스크립트의 비교 *** 

타입스크립트 playground에서 javascript의 변환 내용을 winmerge프로그램을 통해 비교한 결과

타입스크립트에서 타입을 명시하지 않아도 보통 주어진 값으로 추론하기 때문에 

":type"을 명시하지 않아도 된다는 점에서 대부분 비슷하지만, 

Enum과 any부분을 잘 살펴야한다. 

타입스크립트에서 any를 선언하면 타입스크립트에서 탈출하는 키워드이지만, 

타입체크가 이뤄지지않기 때문에 되도록 사용하지 않아야한다. 

 

 

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Data_structures

 

JavaScript의 타입과 자료구조 - JavaScript | MDN

모든 프로그래밍 언어에는 내장된 자료구조가 존재하지만 보통 그 내용은 언어마다 다릅니다. 이 글에서는 JavaScript에서 사용할 수 있는 내장 자료구조와 그 속성에 대해 알아보겠습니다. 그러

developer.mozilla.org

https://typescript-kr.github.io/pages/basic-types.html

 

TypeScript 한글 문서

TypeScript 한글 번역 문서입니다

typescript-kr.github.io

728x90