포스트

2024.06.17 프로그래머스 - 타입스크립트 입문 1

타입스크립트란 (Type Script)?

자바스크립트의 슈퍼셋 언어이다!

  • TS 환경에서 JS는 돌아가지만, JS 환경에서 TS코드는 수행되지 않는다.

자바스크립트에 타입 체크 기능을 포함한 언어이다.

타입 스크립트란 왜 필요한가?

  • JS 코드는 타입이 지정되어 있지 않기 떄문에, 자유도가 높아 코드가 지저분해질 확률이 높다.
  • 코드의 스케일이 커지면서 코드 관리가 되지 않는다.

TS 를 사용하면 좋은 점

  • JS 기반 보다 버그 를 줄일 수 있다.
  • 유지보수가 쉽다.
  • 높은 퀄리티의 강력한 코드를 생산할 수 있다.
  • 정적언어의 특징인 컴파일 단계에서 IDE의 도움으로 버그 및 기타 오류를 발견하기 쉽다.

코드로 보는 TS 와 JS 비교

  • TS 예시 코드

    1
    2
    3
    4
    
      // 간단한 덧셈 함수
      function add (a : number, b : number) {
      	return a + b;
      } 
    
  • JS 예시 코드

    1
    2
    3
    
      function add (a,b) {
      	return a + b;
      }
    

JS 코드에서는, add 함수를 호출할 때, 넘겨주는 인자에 number형이 강제되어있지 않기 때문에, 다른 자료형 값을 인자로 넣어 호출할 수 있고, 이에 대한 에러를 실행 시에만 확인할 수 있다. 하지만 TS에서는 add함수의 인자에 타입을 지정하여 놓았기 때문에 함수를 호출할 때, 지정된 자료형이 아닌 인자값을 넘겨주려고 한다면, 컴파일러 또는 IDE 가 자동으로 타입추론에 대한 오류를 감지하여 에러를 알려준다. 즉 , 실행이 안된다!

타입스크립트와 컴파일

TS는 웹브라우저에서 실행 될 수는 없는 언어이다.

그래서 TS로 작성된 코드는 JS로 컴파일 과정을 지나 JS로 변환되고,

이렇게 변환된 JS 코드가 웹브라우저 상에서 수행되는것.

때문에 정적언어의 특징인 컴파일 (변환과정) 을 거치기 때문에

정적언어의 장점을 살릴 수 있다.

(C언어같이 C언어 → 컴파일 → 원시코드 같은 과정과 같다.)

타입스크립트 사용해보기

TS 사용 환경 설정

  • VSCODE 를 이용하여 TS 사용 환경을 만든다.
  • 확장 프로그램 (Extension) 추가
    • Prettier - Code formatter : 코드 가독성 자동 수정
    • ESLint : 코드 품질 도구
  • Node.js 설치 확인

  • Type Script 설치 명령

    1
    
      npm i -g typescript
    

    이제 tsc 명령어 (TS 명령어) 를 사용할 수 있다.

  • 타입스크립트는 .ts 확장자 (.js 는 .ts로) 파일에서 작성 가능하다.

간단한 TS 함수 만들기

1
2
3
4
5
6
7
// app.ts
function logName(name: string) {
  console.log(name);
}

logName("Test");

  • TS는 js 파일처럼 바로 실행할 수 없고, JS로 컴파일 과정을 한 번 진행해야 한다.
    • tsc 파일이름 명령어로, TS 파일을 JS로 변환 후, node 명령어 또는 디버깅으로 js파일을 실행

TS config 생성

  • tsconfig.json파일은 TS 사용환경에서 사용할 세팅 파일이다.
  • tsc --init 명령어로 해당 config 파일을 자동으로 만들 수 있다.

  • 초기 tsconfig.json 파일
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "js": "preserve",                                /* Specify what js code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsFactory": "",                                 /* Specify the js factory function used when targeting React js emit, e.g. 'React.createElement' or 'h'. */
    // "jsFragmentFactory": "",                         /* Specify the js Fragment reference used for fragments when targeting React js emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsImportSource": "",                            /* Specify module specifier used to import the js factory functions when using 'js: react-js*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' js emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
    // "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */
    // "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */
    // "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

  • tsc -w ts파일이름 ts파일을 감시 할 수 있고, 감시중인 파일에 변경이 발생하면, 해당 파일을 저장시 바로 JS코드로 컴파일 한다.

TS의 데이터 타입과 추론

  • JS는 기대하는 자료형에 대한 입력을 강제하지 못한다.
  • TS는 타입 추론 과정을 통해, 사용했던 변수의 자료형을 지정하여, 다른 자료형이 할당되려고 할 때 사전에 방지 할 수 있다.
1
2
let fullName = "Test man";
fullName = 123;

위 와 같은 코드를 JS 로 컴파일 하면, 경고 메세지가 발생한다.

app.ts:2:1 - error TS2322: Type ‘number’ is not assignable to type ‘string’.

TS 컴파일러가, 이미 string이 할당 되었던 fullName 변수의 타입을 string형으로 인지하고,

이에 대한 기대 자료형이 아닌 number 형 값이 할 당 되려고 할 때 에러 메세지를 발생 시킨다.

TS의 이러한 타입 추론 기능을 통해 유용한 변수 사용이 가능하다.

(타입 표기를 하지 않고, 할당된 값을 통해 변수가 어떤 자료형을 가지는지 스스로 유추한다)

타입 추론 기능 (Type Inference)

  • TS 는 타입 추론 기능을 통해 타입을 자동으로 판단할 수 있다.
  • TS 컴파일러가 변수의 초기 할당 값을 바탕으로 변수의 타입을 추론한다.
  • 타입추론 또한 모호한 타입을 명확히 판단할 수 없기 때문에 타입 명시 를 사용해야 한다.
1
2
3
4
5
6
7
8
9
10
let student = {
  name: "dev",
  course: "type script",
  age: 20,
  city: "seoul",
  grade: () => {
    console.log("A+");
  },
};

위와 같은 변수를 생성해도, TS 컴파일러는 내부 Property들을 통해 타입을 추론한다.

1
2
3
4
5
6
7
let student: {
    name: string;
    course: string;
    age: number;
    city: string;
    grade: () => void;
}

이떄도 프로퍼티에 다른 자료형을 할당하려고 하면 에러가 발생 한다.

1
2
student.name = 123;
//Type 'number' is not assignable to type 'string'.ts(2322)

TS 지원 데이터 타입

  • 기본 데이터 타입
    • string : 문자열
    • number : 정수 , 실수
    • boolean : 참, 거짓
    • null : 값이 없음 타입
    • undefined : 값이 할당되지 않음 타입
  • 객체 타입
    • object : 객체 타입
    • array : 동일한 타입의 요소를 가진 배열 타입
    • tuple : 각 요소가 다른 타입을 가질 수 있는 배열 타입
  • 특수 타입
    • any : 어떤 타입이든 할당 되는 타입
      • 사용을 지양 해야 할 타입
    • unknown : 타입을 미리 알 수 없는 경우 지정하는 타입

TS 의 타입 명시

  • 변수를 선언할 때, 변수 값의 타입을 명시 함으로써 변수의 데이터 타입을 지정
1
let name : string = "문자열 타입 명시"
  • 변수 이름 뒤에 콜론 : 을 이용하여 데이터 타입을 명시 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 일반 변수의 타입 명시
let id : string = "ID";
let password : number = 1234;
let isSuccess : boolean = true;
let getGrade: () => void = () => {
  console.log("A+");
};

// 객체의 타입 명시
let student: {
  name: string;
  course: string;
  age: number;
  city: string;
  male: boolean;
  grade: () => void;
} = {
  name: "dev",
  course: "type script",
  age: 20,
  city: "seoul",
  male: true,
  grade: () => {
    console.log("A+");
  },
};

1
2
3
4
5
6
7
// 함수의 데이터 타입
// 매개변수와 반환 값의 타입을 명시 할 수 있다.
function add (a: number, b : number) : number { // 리턴 타입은 매개변수 선언 뒤에 명시한다.
	return a + b;
}

// 함수가 아무것도 반환하지 않을 때는 void 타입으로 반환 타입을 지정해주면 된다.

타입 명시를 위한 인터페이스

  • 인터페이스의 본질은 결국 사용자가 정의한 타입 이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface Student {
  name: string;
  course: string;
  age?: number; // 선택적 프로퍼티 : 있으면 사용, 없으면 그만인 프로퍼티로 설정
  city: string;
  male: boolean;
  grade: () => void;
}

let student: Student = {
  name: "dev",
  course: "type script",
  age: 20,
  city: "seoul",
  male: true,
  grade: () => {
    console.log("A+");
  },
};
  • interface를 지정하여, 재사용 가능한 사용자 정의 타입을 생성 할 수 있다.

  • 인터페이스 implements 키워드를 통해 class에 대한 타입을 명시 할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
interface Student {
  name?: string;
  course?: string;
  age?: number;
  city?: string;
  male?: boolean;
  grade?: () => void;
  setName: (name: string) => void;
  getName: () => string;
}

class MyStudent implements Student {
  name = "Test man";
  course = "TS";
  age = 123;
  city = "busan";
  male = true;
  setName(name: string): void {
    this.name = name;
    console.log("이름 설정 : " + this.name);
  }
  getName(): string {
    console.log("사용자 이름 : " + this.name);
    return this.name;
  }
}

const myInstance = new MyStudent();
myInstance.setName("kdman"); // "이름 설정 : kdman"
myInstance.getName(); // "사용자 이름 : kdman"

  • implements 키워드로 interface를 class의 템플릿 으로 지정이 가능하다.
  • 인터페이스의 클래스 상속은, 구현 의 개념이고 extends와 다르게 확장 의 개념이 없다.

TS의 열거형

  • 열거형 또한 본질은 사용자 정의 타입이다.

열거형으로 이름이 있는 상수들의 집합을 정의할 수 있습니다. 열거형을 사용하면 의도를 문서화 하거나 구분되는 사례 집합을 더 쉽게 만들수 있습니다. TypeScript는 숫자와 문자열-기반 열거형을 제공합니다. - TypeScript- https://www.typescriptlang.org/ko/docs/handbook/enums.html

1
2
3
4
5
6
7
8
9
10
11
enum GenderType {
  Male,
  Female,
}

enum GradeType {
  A = "A",
  B = "B",
  C = "C",
}

  • 숫자형 열거형은 최초의 멤버 (0) 부터 1씩 증가한 값이 그 멤버의 값이 된다.
  • 위의 코드를 JS로 변환한 결과

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
      var GenderType;
      (function (GenderType) {
          GenderType[GenderType["Male"] = 0] = "Male";
          GenderType[GenderType["Female"] = 1] = "Female";
      })(GenderType || (GenderType = {}));
      var GradeType;
      (function (GradeType) {
          GradeType["A"] = "A";
          GradeType["B"] = "B";
          GradeType["C"] = "C";
      })(GradeType || (GradeType = {}));
    
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.