2woongjae@gmail.com
2woongjae@gmail.com
컴파일러
C. 에디터
A. 실행 환경
B. 컴파일러
Chrome's
V8 JavaScript Engine
을 사용하여,
자바스크립트를 해석하고
OS 레벨에서의 API를 제공하는
서버사이드 용
자바스크립트 런타임 환경
HTML 을 동적으로 만들기 위해
브라우저에서
자바스크립트를 해석하고,
DOM 을 제어할 수 있도록 하는
자바스크립트 런타임 환경
// in config/base.json
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true
  }
}
// in tsconfig.json
{
  "extends": "./configs/base",
  "files": [
    "main.ts",
    "supplemental.ts"
  ]
}{
    "type": "object",
    "description": "Instructs the TypeScript compiler how to compile .ts files.",
    "properties": {
        "charset": {
            "description": "The character set of the input files.",
            "type": "string"
        },
        "declaration": {
            "description": "Generates corresponding d.ts files.",
            "type": "boolean"
        },
        "declarationDir": {
            "type": "string",
            "description": "Specify output directory for generated declaration files. Requires TypeScript version 2.0 or later."
        },
        "diagnostics": {
            "description": "Show diagnostic information.",
            "type": "boolean"
        },
        "emitBOM": {
            "description": "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.",
            "type": "boolean"
        },
        "inlineSourceMap": {
            "description": "Emit a single file with source maps instead of having a separate file.",
            "type": "boolean"
        },
        "inlineSources": {
            "description": "Emit the source alongside the sourcemaps within a single file; requires --inlineSourceMap to be set.",
            "type": "boolean"
        },
        "jsx": {
            "description": "Specify JSX code generation: 'preserve', 'react', or 'react-native'.",
            "enum": [ "preserve", "react", "react-native" ]
        },
        "reactNamespace": {
            "description": "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit.",
            "type": "string"
        },
        "listFiles": {
            "description": "Print names of files part of the compilation.",
            "type": "boolean"
        },
        "locale": {
            "description": "The locale to use to show error messages, e.g. en-us.",
            "type": "string"
        },
        "mapRoot": {
            "description": "Specifies the location where debugger should locate map files instead of generated locations",
            "type": "string"
        },
        "module": {
            "description": "Specify module code generation: 'none', 'CommonJS', 'Amd', 'System', 'UMD', or 'es2015'.",
            "enum": [ "commonjs", "amd", "umd", "system", "es6", "es2015", "none" ]
        },
        "newLine": {
            "description": "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).",
            "enum": [ "CRLF", "LF" ]
        },
        "noEmit": {
            "description": "Do not emit output.",
            "type": "boolean"
        },
        "noEmitHelpers": {
            "description": "Do not generate custom helper functions like __extends in compiled output.",
            "type": "boolean"
        },
        "noEmitOnError": {
            "description": "Do not emit outputs if any type checking errors were reported.",
            "type": "boolean"
        },
        "noImplicitAny": {
            "description": "Warn on expressions and declarations with an implied 'any' type.",
            "type": "boolean"
        },
        "noImplicitThis": {
            "description": "Raise error on 'this' expressions with an implied any type.",
            "type": "boolean"
        },
        "noUnusedLocals": {
            "description": "Report errors on unused locals. Requires TypeScript version 2.0 or later.",
            "type": "boolean"
        },
        "noUnusedParameters": {
            "description": "Report errors on unused parameters. Requires TypeScript version 2.0 or later.",
            "type": "boolean"
        },
        "noLib": {
            "description": "Do not include the default library file (lib.d.ts).",
            "type": "boolean"
        },
        "noResolve": {
            "description": "Do not add triple-slash references or module import targets to the list of compiled files.",
            "type": "boolean"
        },
        "skipDefaultLibCheck": {
            "type": "boolean"
        },
        "skipLibCheck": {
            "description": "Skip type checking of declaration files. Requires TypeScript version 2.0 or later.",
            "type": "boolean"
        },
        "outFile": {
            "description": "Concatenate and emit output to single file.",
            "type": "string"
        },
        "outDir": {
            "description": "Redirect output structure to the directory.",
            "type": "string"
        },
        "preserveConstEnums": {
            "description": "Do not erase const enum declarations in generated code.",
            "type": "boolean"
        },
        "pretty": {
            "description": "Stylize errors and messages using color and context (experimental).",
            "type": "boolean"
        },
        "removeComments": {
            "description": "Do not emit comments to output.",
            "type": "boolean"
        },
        "rootDir": {
            "description": "Specifies the root directory of input files. Use to control the output directory structure with --outDir.",
            "type": "string"
        },
        "isolatedModules": {
            "description": "Unconditionally emit imports for unresolved files.",
            "type": "boolean"
        },
        "sourceMap": {
            "description": "Generates corresponding '.map' file.",
            "type": "boolean"
        },
        "sourceRoot": {
            "description": "Specifies the location where debugger should locate TypeScript files instead of source locations.",
            "type": "string"
        },
        "suppressExcessPropertyErrors": {
            "description": "Suppress excess property checks for object literals.",
            "type": "boolean"
        },
        "suppressImplicitAnyIndexErrors": {
            "description": "Suppress noImplicitAny errors for indexing objects lacking index signatures.",
            "type": "boolean"
        },
        "stripInternal": {
            "description": "Do not emit declarations for code that has an '@internal' annotation.",
            "type": "boolean"
        },
        "target": {
            "description": "Specify ECMAScript target version. Permitted values are 'es3', 'es5', 'es2015', 'es2016', 'es2017' or 'esnext'.",
            "type": "string",
            "default": "es3",
            "anyOf": [
                {
                    "enum": [
                        "es3",
                        "es5",
                        "es2015",
                        "es2016",
                        "es2017",
                        "esnext"
                      ]
                }, {
                      "pattern": "^([eE][sS]([356]|(201[567])|[nN][eE][xX][tT]))$"
                }
            ]
        },
        "watch": {
            "description": "Watch input files.",
            "type": "boolean"
        },
        "experimentalDecorators": {
            "description": "Enables experimental support for ES7 decorators.",
            "type": "boolean"
        },
        "emitDecoratorMetadata": {
            "description": "Emit design-type metadata for decorated declarations in source.",
            "type": "boolean"
        },
        "moduleResolution": {
            "description": "Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6) .",
            "type": "string",
            "pattern": "^(([Nn]ode)|([Cc]lassic))$",
            "default": "classic"
        },
        "allowUnusedLabels": {
            "type": "boolean",
            "description": "Do not report errors on unused labels."
        },
        "noImplicitReturns": {
            "description": "Report error when not all code paths in function return a value.",
            "type": "boolean"
        },
        "noFallthroughCasesInSwitch": {
            "description": "Report errors for fallthrough cases in switch statement.",
            "type": "boolean"
        },
        "allowUnreachableCode": {
            "description": "Do not report errors on unreachable code.",
            "type": "boolean"
        },
        "forceConsistentCasingInFileNames": {
            "description": "Disallow inconsistently-cased references to the same file.",
            "type": "boolean"
        },
        "baseUrl": {
            "description": "Base directory to resolve non-relative module names.",
            "type": "string"
        },
        "paths": {
            "description": "Specify path mapping to be computed relative to baseUrl option.",
            "type": "object"
        },
        "rootDirs": {
            "description": "Specify list of root directories to be used when resolving modules.",
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "typeRoots": {
            "description": "Specify list of directories for type definition files to be included. Requires TypeScript version 2.0 or later.",
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "types": {
            "description": "Type declaration files to be included in compilation. Requires TypeScript version 2.0 or later.",
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "traceResolution": {
            "description": "Enable tracing of the name resolution process.",
            "type": "boolean"
        },
        "allowJs": {
            "description": "Allow javascript files to be compiled.",
            "type": "boolean"
        },
        "allowSyntheticDefaultImports": {
            "description": "Allow default imports from modules with no default export. This does not affect code emit, just typechecking.",
            "type": "boolean"
        },
        "noImplicitUseStrict": {
            "description": "Do not emit 'use strict' directives in module output.",
            "type": "boolean"
        },
        "listEmittedFiles": {
            "description": "Enable to list all emitted files. Requires TypeScript version 2.0 or later.",
            "type": "boolean"
        },
        "lib": {
            "description": "Specify library file to be included in the compilation. Requires TypeScript version 2.0 or later.",
            "type": "array",
            "items": {
                "type": "string",
                "enum": [ "es5", "es6", "es2015", "es7", "es2016", "es2017", "esnext", "dom", "dom.iterable", "webworker", "scripthost", "es2015.core", "es2015.collection", "es2015.generator", "es2015.iterable", "es2015.promise", "es2015.proxy", "es2015.reflect", "es2015.symbol", "es2015.symbol.wellknown", "es2016.array.include", "es2017.object", "es2017.sharedmemory", "esnext.asynciterable"
                ]
            }
        },
        "strictNullChecks": {
            "description": "Enable strict null checks. Requires TypeScript version 2.0 or later.",
            "type": "boolean"
        },
        "maxNodeModuleJsDepth": {
            "description": "The maximum dependency depth to search under node_modules and load JavaScript files. Only applicable with --allowJs.",
            "type": "number",
            "default": 0
        },
        "importHelpers": {
            "description": "Import emit helpers (e.g. '__extends', '__rest', etc..) from tslib. Requires TypeScript version 2.1 or later.",
            "type": "boolean"
        },
        "jsxFactory": {
            "description": "Specify the JSX factory function to use when targeting react JSX emit, e.g. 'React.createElement' or 'h'. Requires TypeScript version 2.1 or later.",
            "type": "string",
            "default": "React.createElement"
        },
        "alwaysStrict": {
            "description": "Parse in strict mode and emit 'use strict' for each source file. Requires TypeScript version 2.1 or later.",
            "type": "boolean"
        },
        "strict": {
            "description": "Enable all strict type checking options. Requires TypeScript version 2.3 or later.",
            "type": "boolean"
        },
        "downlevelIteration": {
            "description": "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. Requires TypeScript version 2.3 or later.",
            "type": "boolean"
        },
        "checkJs": {
            "description": "Report errors in .js files. Requires TypeScript version 2.3 or later.",
                "type": "boolean"
        }
    }
}{
    "type": "object",
    "description": "Instructs the TypeScript compiler how to compile .ts files.",
    "properties": {
        "typeRoots": {
            "description": "Specify list of directories for type definition files to be included. Requires TypeScript version 2.0 or later.",
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "types": {
            "description": "Type declaration files to be included in compilation. Requires TypeScript version 2.0 or later.",
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    }
}{
    "type": "object",
    "description": "Instructs the TypeScript compiler how to compile .ts files.",
    "properties": {
        "target": {
            "description": "Specify ECMAScript target version. Permitted values are 'es3', 'es5', 'es2015', 'es2016', 'es2017' or 'esnext'.",
            "type": "string",
            "default": "es3",
            "anyOf": [
                {
                    "enum": [
                        "es3",
                        "es5",
                        "es2015",
                        "es2016",
                        "es2017",
                        "esnext"
                      ]
                }, {
                      "pattern": "^([eE][sS]([356]|(201[567])|[nN][eE][xX][tT]))$"
                }
            ]
        },
        "lib": {
            "description": "Specify library file to be included in the compilation. Requires TypeScript version 2.0 or later.",
            "type": "array",
            "items": {
                "type": "string",
                "enum": [ "es5", "es6", "es2015", "es7", "es2016", "es2017", "esnext", "dom", "dom.iterable", "webworker", "scripthost", "es2015.core", "es2015.collection", "es2015.generator", "es2015.iterable", "es2015.promise", "es2015.proxy", "es2015.reflect", "es2015.symbol", "es2015.symbol.wellknown", "es2016.array.include", "es2017.object", "es2017.sharedmemory", "esnext.asynciterable"
                ]
            }
        },
        "noLib": {
            "description": "Do not include the default library file (lib.d.ts).",
            "type": "boolean"
        }
    }
}{
    "type": "object",
    "description": "Instructs the TypeScript compiler how to compile .ts files.",
    "properties": {
        "outFile": {
            "description": "Concatenate and emit output to single file.",
            "type": "string"
        },
        "outDir": {
            "description": "Redirect output structure to the directory.",
            "type": "string"
        },
        "rootDir": {
            "description": "Specifies the root directory of input files. Use to control the output directory structure with --outDir.",
            "type": "string"
        }
    }
}{
    "type": "object",
    "description": "Instructs the TypeScript compiler how to compile .ts files.",
    "properties": {
        "module": {
            "description": "Specify module code generation: 'none', 'CommonJS', 'Amd', 'System', 'UMD', or 'es2015'.",
            "enum": [ "commonjs", "amd", "umd", "system", "es6", "es2015", "none" ]
        },
        "moduleResolution": {
            "description": "Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6) .",
            "type": "string",
            "pattern": "^(([Nn]ode)|([Cc]lassic))$",
            "default": "classic"
        },
        "baseUrl": {
            "description": "Base directory to resolve non-relative module names.",
            "type": "string"
        },
        "paths": {
            "description": "Specify path mapping to be computed relative to baseUrl option.",
            "type": "object"
        },
        "rootDirs": {
            "description": "Specify list of root directories to be used when resolving modules.",
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    }
}오브젝트와 레퍼런스 형태가 아닌 실제 값을 저장하는 자료형입니다.
프리미티브 형의 내장 함수를 사용 가능한것은 자바스크립트 처리 방식 덕분
let name = 'mark';
name.toString();값자체가 변하지 않는 값을 의미합니다.
상수와 다른 것은 상수는 가리키는 포인터가 고정이라는 것이고, 리터럴은 그 자체가 값이자 그릇입니다.
35; // number 리터럴
'mark' // string 리터럴
true // boolean 리터럴
// object 리터럴
{
    name: 'mark',
    age: 35
}값자체가 변하지 않는 값을 의미합니다.
상수와 다른 것은 상수는 가리키는 포인터가 고정이라는 것이고, 리터럴은 그 자체가 값이자 그릇입니다.
"리터럴 상수는 5, 1.23 과 같은 숫자나, 과 같은 문자열 등을 말합니다. 'This is a string' 혹은 "It’s a string!"이것들이 리터럴 상수라고 불리우는 이유는 이것들이 프로그램 내에 직접 문자 형태로(literally)지정되는 값들이기 때문입니다. 이러한 값들은 한번 지정되면 변하지 않습니다. 예를 들면 숫자2 는 언제나 자기 자신이 2라는 숫자임을 나타내며 어떤 다른 의미도 갖지 않습니다. 이들은 한번 지정되면 그 값을 변경할 수 없기 때문에 _상수_입니다. 그 중에서도 특별히 이러한 값들을 리터럴 상수라고 부릅니다." @kangpual
가장 기본적인 데이터 타입
단순한 true 혹은 false 값 입니다.
JavaScript / TypeScript 에서 'boolean' 이라고 부른다.
let isDone: boolean = false;
typeof isDone === 'boolean' // true
// Type 'boolean' is assignable to type 'Boolean'.
let isOk: Boolean = true;
// Type 'Boolean' is not assignable to type 'boolean'.
// 'boolean' is a primitive, but 'Boolean' is a wrapper object.
// Prefer using 'boolean' when possible.
let isNotOk: boolean = new Boolean(true);JavaScript 와 같이, TypeScript 의 모든 숫자는 부동 소수점 값 입니다.
TypeScript는 16진수 및 10진수 리터럴 외에도, ECMAScript 2015에 도입된 2진수 및 8진수를 지원합니다.
let decimal: number = 6; // 10진수 리터럴
let hex: number = 0xf00d; // 16진수 리터럴
let binary: number = 0b1010; // 2진수 리터럴
let octal: number = 0o744; // 8진수 리터럴다른 언어에서와 마찬가지로이 텍스트 형식을 참조하기 위해 `string` 형식을 사용합니다.
JavaScript 와 마찬가지로, TypeScript는 문자열 데이터를 둘러싸기 위해 큰 따옴표 ( " ) 나, 작은 따옴표 ( ' ) 를 사용합니다.
let name: string = "mark";
name = 'anna';행에 걸쳐 있거나, 표현식을 넣을 수 있는 문자열
이 문자열은 backtick (= backquote) 기호에 둘러쌓여 있습니다.
포함된 표현식은 `${ expr }` 와 같은 형태로 사용합니다.
let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ fullName }.
I'll be ${ age + 1 } years old next month.`;
// template string 을 사용하지 않을 경우
let sentence: string = "Hello, my name is " + fullName + ".\n\n" +
    "I'll be " + (age + 1) + " years old next month.";TypeScript 에서 'undefined' 와 'null' 은 실제로 각각 'undefined' 와 'null' 이라는 고유한 타입을가집니다.
'void' 와 마찬가지로, undefined 와 null 은 그 자체로는 쓸모가 없습니다.
둘다 소문자만 존재합니다.
// 이 변수들에 할당할 수 있는 것들은 거의 없다.
let u: undefined = undefined;
let n: null = null;기본 설정이 그렇습니다.
number 에 null 또는 undefined 를 할당할 수 있다는 의미입니다.
하지만, 컴파일 옵션에서 `--strictNullChecks`사용하면, null 과 undefined 는 void 나 자기 자신들에게만 할당할 수 있습니다.
이 경우, null 과 undefined 를 할당할 수 있게 하려면, union type 을 이용해야 합니다.
let name: string = null;
let age: number = undefined;
// strictNullChecks => true
// Type 'null' is not assignable to type 'string'.
let name: string = null; (X)
// null => null || void, undefined => undefined || void
// Type 'null' is not assignable to type 'undefined'.
let u: undefined = null; // (X)
let v: void = undefined; // (O)
let union: string | null | undefined = 'str';null 이라는 값으로 할당된 것을 null 이라고 합니다.
무언가가 있는데, 사용할 준비가 덜 된 상태.
null 이라는 타입은 null 이라는 값만 가질 수 있습니다.
런타임에서 typeof 연산자를 이용해서 알아내면, object 입니다.
let n: null = null;
console.log(n); // null
console.log(typeof n); // object값을 할당하지 않은 변수는 undefined 라는 값을 가집니다.
무언가가 아예 준비가 안된 상태
object 의 property 가 없을 때도 undefined 입니다.
런타임에서 typeof 연산자를 이용해서 알아내면, undefined 입니다.
let u: undefined = undefined;
console.log(u); // undefined
console.log(typeof u); // undefined타입이 없는 상태입니다.
`any` 와 반대의 의미를 가집니다.
Void 는 없습니다. 소문자입니다.
주로 함수의 리턴이 없을 때 사용합니다. 그 외에는 사용할 일이 거의 없습니다.
function returnVoid(message): void {
    console.log(message);
}
returnVoid('리턴이 없다');어떤 타입이어도 상관없는 타입입니다.
이걸 최대한 쓰지 않는게 핵심입니다.
왜냐면 컴파일 타임에 타입 체크가 정상적으로 이뤄지지 않기 때문입니다.
그래서 컴파일 옵션 중에는 any 를 쓰면 오류를 뱉도록 하는 옵션도 있습니다.
noImplicitAny
function returnAny(message): any {
    console.log(message);
}
returnVoid('리턴은 아무거나');리턴에 주로 사용됩니다.
아래 3가지 정도의 경우가 대부분입니다.
// Function returning never must have unreachable end point
function error(message: string): never {
    throw new Error(message);
}
// Inferred return type is never
function fail() {
    return error("Something failed");
}
// Function returning never must have unreachable end point
function infiniteLoop(): never {
    while (true) {
    }
}원래 자바스크립트에서 array 는 객체입니다.
사용방법
Array<타입>
타입[]
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];배열인데 타입이 한가지가 아닌 경우
마찬가지로 객체입니다.
꺼내 사용할때 주의가 필요합니다.
배열을 Destructuting 하면 타입이 제대로 얻어집니다.
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
x[3] = "world"; // OK, 'string' can be assigned to 'string | number'
console.log(x[5].toString()); // OK, 'string' and 'number' both have 'toString'
x[6] = true; // Error, 'boolean' isn't 'string | number'
const person: [string, number] = ['mark', 35];
const [name, age] = person;C 에서 보던것과 같습니다.
아래 예제만 이해하면 사용 준비 끝
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];ECMAScript 2015 의 Symbol 입니다.
프리미티브 타입의 값을 담아서 사용합니다.
고유하고 수정불가능한 값으로 만들어줍니다.
그래서 주로 접근을 제어하는데 쓰는 경우가 많았습니다.
let sym = Symbol();
let obj = {
    [sym]: "value"
};
console.log(obj[sym]); // "value"