02.TS 문법

Updated:


TypeScript 문법

from 공식 사이트 : (https://www.typescriptlang.org/)

1.TS type vs JS type

📌 TS type vs TS type

Static types (TS) Dynamic types (JS)
set during dev resolved at runtime
개발하는 중간에 type checked 개발할때는 모르고 실제 runtime 시에 type checked
// JS 에서 type 이 안받을때 error 출력 방법
function add(n1, n2) {
  if (typeof n1 !== "number" || typeof n2 !== "number") {
    throw new Error("Incorrect input!");
  }
  return n1 + n2;
}
// TS 에서 type 설정하기 (위의 JS 와 결과 값은 같음)

function add(n1: number, n2: number) {
  return n1 + n2;
}

const result = add(39, 28);
  • TS 에서 type annotation 해주게 되면 JS 코드에서 runtime 때 error check 해줘야 하는것을 안해줘도 됨

  • 먼저 error 가 발생 할 경우, 한 step 먼저 error 를 check 할 수 있음

📎from TS 공식 사이트 : (https://www.typescriptlang.org/)

  • For programs to be useful, we need to be able to work with some of the simplest units of data: numbers, strings, structures, boolean values and the like

  • 📦 즉, 프로그램이 유용하려면, 가장 간단한 데이터 단위로 작업 할 수 있어야 합니다: numbers, strings, structures, boolean 값 등등

  • In TypeScript, we support the same types as you would expect in JavaScript, with an extra enumeration type thrown in to help things along.

  • TypeScript에서 프로그램 작성을 위해 기본 제공하는 데이터 타입

  • 사용자가 만든 타입은 결국 이 기본 자료형들로 나눠 집니다

    • ECMAScript 표준에 따른 기본 자료형은 6가지

      • Boolean

      • Number

      • String

      • Null

      • Underfined

      • Symbol (EC6 에서 추가됨)

      • Array : object 형

    • 프로그래밍을 도울 몇가지 타입이 더 사용됩니다.

      • Any, Void, Never, Unknown

      • Enum

      • Tuple : object 형

2.Primitive Types

📌 Object, Reference 형태가 아닌 실제 값을 저장하는 자료형입니다.

📌 Primitive Type 형의 내장 함수를 사용 가능한것은 자바스크립트 처리 방식 덕분입니다.

  • (ES2015 기준) 6가지

    • boolean

    • number

    • string

    • symbol (ES2015)

    • null

    • underfined

let name = "mark";

name.toString();
  • literal 값으로 primitive 타입의 서브 타입을 나타낼 수 있습니다.
true; //  전체 boolean type 중에 sub-type 인 true

("hello"); // 전체 string type 중에 sub-type 인 'hello'

3.14; // 전체 number type 중에 sub-type 인 3.14

null;

underfined;
  • JS 에서는 래퍼 객페로 해서 만들어줌
new Boolean(false); // typeof new Boolean(false) : 'object'

new String("world"); // typeof new String('world') : 'object'

new Number(42); // typeof new Number (42) : 'object'

Type Casing

from 공식 사이트 : (https://www.typescriptlang.org/)

  • The code primitive types in TypeScript are all lowecase. (TypeScript의 핵심 primitive types 은 모두 소문자 입니다)

  • It can be tempting to think that the types Number, String, Boolean, Symbol, or Object are the same as the lowercase version recommended above. (Number, String, Boolean, Symbol 또는 Object 유형이 위에서 권장한 소문자 버전과 동일하다고 할 수 있습니다.)

  • These types do not refer to the language primitives however, and almost never should be used as a type. (그러나 이러한 유형은 primitives 를 나타내지 않으며, 타입으로 사용해서는 안됩니다)

function reverse(s: String): String {
  // 대문자로 타입 사용하면 안됩!!
  return s.split("").reverse().join("");
}

reverse("hello world");
  • Instead, use the types number, string, boolean, object and symbol
function reverse(s: string): string {
  // 소문자로 사용
  return s.split("").reverse().join("");
}

reverse("hello world");

🔹 복습!! Project 폴더에 TS 실습환경 설치

  1. Create proper folder

  2. npm init -y // 프로젝트 지역에 node.js 설치

  3. npm install typescript -D // TS -devDependencies 모드로 설치

  4. npx tsc --init // root 경로에 tsconfig.json 파일 생성

  5. npx tsc // 컴파일 실행

  6. node 파일명.js // 컴파일 한 js 파일 실행 명령

3.boolean

let isDone: boolean = false; // 소문자 가능

isDone = true;



console.log(typeof isDone); // `boolean`


------------------------------------------------


let isOk: Boolean = true; // 되도록이면 소문자를 사용해야 함


// `boolean` is a primitive, but 'Boolean' is a warpper object. Prefer using `boolean` when possible.
let isnotOk: boolean = new Boolean(true); // error

4.number

  • JS와 같이, TS 의 모든 숫자는 부동 소수점 값 입니다.

  • TS는 16진수 및 10진수 literal 외에도 ECMAScript 2015에서 도입된 2진수 및 8진수를 지원합니다.

  • NaN

  • 1_000_000 과 같은 표기도 가능합니다.

let decimal: number = 6; // 십진수

let hex: number = 0xf000d; // 16진수

let binary: number = 0b1010; // 2진수

let octal: number = 0o744; // 8진수

let notANumber: number = NaN;

let underscoreNum: number = 1_000_000;

5.string

  • 다른언어와 마찬가지로 이 텍스트 형식을 참조하기 위해 string (backtick)형식을 사용합니다

  • JS 와 마찬가지로, TS 는 문자열 데이터를 둘러싸기 위해 ““(quotaion mark), ‘‘(apostrophe)

let myName: string = "Jacob";

myName = "Emma";

Template String

  • 행에 걸쳐 있거나, 표현식을 넣울 수 있는 문자열

  • 이 문자열은 backtick(=backquote) 기호에 둘러 쌓여 있습니다

  • 포함된 표현식은 ${expr} 와 같은 형태로 사용합니다.

6.symbol

  • ECMAScript 2015의 symbol 입니다.

  • new Symbol 로 사용할 수 없습니다.

  • Symbol 을 함수로 사용해서 symbol 타입을 만들어낼 수 있습니다.

// console.log(Symbol('foo')) // error 발생 -> Symbol only refers to a type. but is being used as a value here.

// 임시로 symbol 사용할 수 있게 tsconfig.json 에서 "lib": ["ES2015", "DOM"], 에서 조절 한다음에 임시로 사용가능하게 조절

console.log(Symbol("foo") === Symbol("foo")); // false 출력 -> 다른 메모리로 나옴

symbol 이 사용되는 경우

  • 프리미티브 타입의 값을 담아서 사용합니다.

  • 고유하고 수정불가능한 값으로 만들어줍니다.

  • 그래서 주로 접근을 제어하는데 쓰는 경우가 많았습니다.

7.undefined & null

  • In TypeScript, both underfined and null actially have their types named underfined and null respectively. (TypeScript에서 undefined 와 nul 은 실제로 각각 undefined 및 null 이라는 타입을 가집니다.)

  • Much like void, they’re not extremely useful on their own: (void와 마찬가지로, 그 자체로는 그다지 유용하지 않습니다.)

  • 둘다 소문자만 손재합니다.

// 이 변수들에 할당할 수 있는 것들은 거의 없다.

let u: underfined = undefined;
let n: null = null;

underfined & null are subtypes of all other types.

  • 설정을 하지 않으면 그렇습니다.

  • number에 null 또는 underfined를 할당할 수 있다는 의미입니다.

  • 하지만, 컴파일 옵션에서 --strictNullChecks 사용하면, nullundefinedvoid 나 자기 자신들에게 만 할당할 수 있습니다.

    • 이 경우, nullundefined 를 할당할 수 있게 하려면, union type 을 이용해야 합니다.
let Myname: string = null; // 이렇게 쓰면 안됨
let age: number = underfined;

// strickNulllCjecks => true
// Type `null` is not assignable to type `string`.
let name: string = null;
X;

// null => null || voidm underfined => undefined || void
// Type `null` is not assignable to type 'underfined'
let u: undefined = null; // (X)

let v: void = undefined; // (O)

let union: string | null | undefined = "str"; // 교집합인 | 을 사용해야 함

null in JavaScript

  • null 이라는 값으로 할당된 것을 null 이라고 합니다.

  • 무언가가 있는데, 사용할 준비가 덜 된 상태.

  • null 이라는 타입은 null 이라는 값만 가질 수 있습니다.

  • 런타임에서 typeof 연산자를 이용해서 알아내면, object 입니다

let n: null = null;

console.log(n); // null
console.log(typeof n); // object

undefined in JavaScript

  • 값을 할당하지 않은 변수는 undefined 라는 값을 가집니다.

  • 무언가가 아예 준비가 안된 상태

  • object 의 property가 없을 때도 undefined 입니다.

  • 런타임에서 typeof 연산자를 이용해서 알아내면, undefined 입니다.

let u: undefined = undefinde;

console.log(u); // undefined
console.log(typeof u); // undefined

8.object

  • a type that represents the non-promitive type (“promitive type 이 아닌것” 을 나타내고 싶을 때 사용하는 타입)

  • non-primitive type : not number, string, boolean, bigint, symbol, null, or undefined

// create by object literal
const person1 = { name: "Jacob", age: 80 };

// person1 is not "object" type.
// person1 is "{name: string, age: number}" type.

// create by Object.create
const person2 = Object.create({ name: "Jacob", age: 80 });

const person3 = Object.create(80); // 이런것을 막기 위해 object type 이 존재하는것임

// object 사용 예제

let obj: object = {};

obj = { name: "Jacob" };

obj = [{ name: "Jacob" }];

obj = 80; // Error

obj = "Jacob"; // Error

obj = true; // Error

obj = 100n; // Error

obj = Symbol(); // Error

obj = null; // Error

obj = undefined; // Error

declare function create(o: object | null): void; // premitive type 을 받지 않는경우에 사용

create({ prop: 0 });

create(null);

create(42); // Error

create("string"); // Error

create(false); // Error

create(undefined); // Error

// Object.create
Object.create(0); // Error

9.Array

  • 원래 JavaScript 에서 array 는 객체입니다.

  • 사용방법

    • Array<타입>

    • 타입[] -> 이 방식을 주로 사용함!!

// Array 선언방식은 2가지가 있음 근데, 첫번째 방식을 사용하는것을 추천함.
let list1: number[] = [1, 2, 3];

let list2: Array<number> = [1, 2, 3];

let list3: (number | string)[] = [1, 2, 3, "4"]; // array 안에 str 을 넣으려면 union type | 을 써서 사용할 수 있음

10.Tuple

// tuple
let x: [string, number];

x = ["hello", 80]; // 항상 순서도 맞아야 되고, type 도 맞아야 되고 index 길이도 맞아야 됨

x = [10, "Jacob"]; // Error;

x[3] = "world"; // index 길이가 맞지 않아서 Error

const person: [string, number] = ["Jacob", 80];

const [first, second, third] = person; // deconstruction 분해 할당 , index number Error

11.any

  • 어떤 타입이어도 상관없는 타입입니다.

  • 이걸 최대한 쓰지 않는게 핵심입니다.

  • 왜냐하면 컴파일 타임에 타입 체크가 정상적으로 이뤄지지 않기 때문입니다.

  • 그래서 컴파일 옵션 중에는 any 를 써야 하는데 쓰지 않으면 오류를 뱉도록 하는 옵션도 있습니다.

    • nolmiplicitAny
  • The any will continue to progagate through your objects: (any는 계속해서 개체를 통해 전파됩니다.)

  • After all, remember that all the convenience ofany comes at the cost of losing type safely. (결국, 모든 편의는 타입 안정성을 잃는 대가로 온다는 것을 기억하십시오)

  • Type safety is one of the main motivations for using TypeScript and you should try to avoid using any when not necessary. (타입 안정성은 TypeScript 를 사용하는 주요 동기 중 하나이며 필요하지 않은 경우에는 any 를 사용하지 않도록 해야 합니다.)

// any : 아무것도 모른 상태에서 어떤 것이든 할 수 있다 라는 뜻임
function returnAny(message: any): any {
  console.log(message);
}

const any1 = returnAny("리턴은 아무거나 다 됨");

any1.toString();

// 예시

let looselyTyped: any = {};

const d = looselyTyped.a.b.c.d; // 이렇게 막 써도 error 가 나지 않음

function leakingAny(obj: any) {
  const a = obj.num;
  const b = a + 1;
  return b;
}

const c = leakingAny({ num: 0 });
c.indexOf("0");

12.unknown

  • We my need to describe the type of variables that we do not know when we are wrting an application. (응용 프로그램을 장성할 때 모르는 변수의 타입을 묘사해야 할 수도 있습니다.)

  • These values my come from dynamic contect - e.g from the user - or we may want to intentionally accept all balues in our API. (이러한 값은 동적 콘텐츠 (예: 사용자로부터, 또는 우리 API의 모든 값으 ㄹ의도적으로 수락하기를 원할 수 있습니다.))

  • In these cases, we want yo provide a type that tells the compiler and future readers that this variable could be anything, so we give it the unknown type. (이 경우, 컴파일러와 미래의 코드를 읽는 사람에게 이 변수가 무엇이든 될 수 있을을 알려주는 타입을 제공하기를 원하므로 unknown 타입을 제공합니다.)

unknown 정리

  • TypeScript 3.0 버전부터 지원

  • any와 짝으로 any 보다 Type-safe 한 타입

    • any와 같이 아무거나 할당할 수 있다

    • 컴파일러가 타입을 추론할 수 있게 끔 타입의 유형을 좁히거나

    • 타입을 확정해주지 않으면 다른 곳에 할당 할 수 없고, 사용할 수 없다.

  • unknown 타입을 사용하면 runtime error를 줄일 수 있을 것 같다.

    • 사용 전에 데이터의 일부 유형의 검사를 수행해야 함을 알리는 API에 사용할 수 있을 것 같다.
declare const maybe: unknown;

const aNumber: number = maybe;

if (maybe === true) {
  // unknown 이 이제는 boolean 형태로는 받을 수 있게 됨
  const aBoolean: boolean = maybe; // 정상
  const aString: string = maybe; // str 로는 받을 수 없기 때문에 error
}

if (typeof maybe === "string") {
  // unknown 이 이제는 str 형태로 받을 수 있게 됨
  const aString: string = maybe; // 정상
  const aBoolean: boolean = maybe; // 더이상 maybe가 boolean 형태가 아니기 때문에 error 임
}

13.never

  • 일반적으로 return 에 사용됩니다

  • never 타입은 모든 타입의 subtype 이며, 모든 타입에 할당 할 수 있습니다.

  • 하지만, never 에는 그 어떤 것도 할당할 수 없습니다.

  • any 조차도 never 에게 할당 할 수 없습니다.

  • 잘못된 타입을 넣는 실수를 막고자 할 때 사용하기도 합니다.

// 일반적으로 사용되는 never 사용의 예제

function error(message: string): never {
  throw new Error(message); // 어떠한 형태도 return 되지 않는 다는것
}

function fail() {
  return error("failed");
}

function infiniteLoop(): never {
  while (true) {}
}

// 자주 사용되는 예제

let a: string = "hello";

if (typeof a !== "string") {
  a; // a가 never 가 간주 됨에 따라 사전에 잘못된 실수를 막을 수 있음
}

declare const b: string | number;

if (typeof b !== "string") {
  b; // b 가 str 이 아니기 때문에 number 로 됨
}

type Indexable<T> = T extends string ? T & { [index: string]: any } : never; // 조건부 타입:  T 가 만약에  string any 로 가고 아니면 never 가 뜨게 됨

type ObjectIndexable = Indexable<{}>;

const b: Indexable<{}> = ""; // error 발생 위에서 never로 됬기 때문에 안됨

14.void

  • 어떤 타입도 가지지 않는 빈 상태인것을 말합니다

  • 소문자를 사용합니다

  • 값을 반환 하지 않은 즉, undefined 를 return 했다고 보면 됩니다

  • 다른언어 (Java 등)에서 많이 쓰기 때문에, 그냥 용어만 가져 왔다고 보면됨 왜냐면 JS, TS 에는 undefined 가 있기 때문입니다

function returnVoid(message: string) {
  // 아무것도 return 하지 않았기 때문에 void 가 됨
  console.log(message);
  return undefined; // void 에 유일하게 return 할 수 있는것은 undefined 뿐이다.
}

const r = returnVoid("리턴이 없다.");

Reference

Leave a comment