Typescript 개요

cloud2000·2025년 5월 25일

1. Typescript

TypeScript 사용하는 이유

  • TypeScript는 JavaScript 코드를 단순화하여 더 쉽게 읽고 디버그할 수 있도록 한다.
  • TypeScript는 오픈 소스이다.
  • TypeScript는 정적 검사와 같은 JavaScript IDE 및 사례를 위한 매우 생산적인 개발 도구를 제공한다.
  • TypeScript를 사용하면 코드를 더 쉽게 읽고 이해할 수 있다.
  • TypeScript를 사용하면 일반 JavaScript보다 크게 개선할 수 있다.
  • TypeScript는 ES6(ECMAScript 6)의 모든 이점과 더 많은 생산성을 제공한다.
  • TypeScript는 코드 유형 검사를 통해 JavaScript를 작성할 때 개발자가 일반적으로 겪는 고통스러운 버그를 피하는 데 도움이 될 수 있다.
function sayHello(firstName: string) {  // Type Annotation을 붙임
  console.log("Hello " + firstName)
}

let firsName: string = "Cloud.Jung"
sayHello(firstName)

1.2 변수

원시타입

  • 변수 선언에는 let, const를 사용함.
  • 원시타입에는 string, number, boolean만 존재함.
let age: number = 36
let isDone: boolean = true
let color: string = 'blue''

배열

const array: string[] = []
array.push('abc')
array.push(1) // error

const mixedArray = ['foo', 1]
const mixedArrayByUnion: (string|number)[] = ['foo', 1]  // Union
const mixedArrayTuple: [string, number] = ['foo', 1]  // 투플

객체

const user: {name: string, age: number} = {
	name: 'Cloud Jung'
    age: 36
}

console.log(user.name)
console.log(user.age)

function printName(obj: {fristName: string; lastName?: string}) {
	// ...
}

printName({firstName: 'Cloud'})
printName({firstName: 'Cloud', lastName: 'Jung'})
  • 객체는 코드가 길어져서 type alias와 함께 사용하는 경우가 많다.

Any

  • 가급적 any는 사용하지 않는다.

함수

function add(a: number, b: number): number {
  // Function body
  return value;
}

// Using the function keyword
const add = function (a: string): string {
  return value;
};

// Using arrow function syntax
const add = (a: string): string => {
  return value;
};

// optional parameters
function greet(name: string, greeting?: string): string {
  if (greeting) {
    return `${greeting}, ${name}!`;
  }
  return `Hello, ${name}!`;
}

// default parameters
function greetWithDefault(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}

// Rest parameters
function sum(...numbers: number[]): number {
  return numbers.reduce((total, num) => total + num, 0);
}

// Function Overloads
function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: any, b: any): any {
  if (typeof a === 'number' && typeof b === 'number') {
    return a + b;
  }
  if (typeof a === 'string' && typeof b === 'string') {
    return a + b;
  }
  throw new Error("Invalid arguments");
}

// Function Types
type MathOperation = (a: number, b: number) => number;

const add: MathOperation = (x, y) => x + y;

Reference

profile
클라우드쟁이

0개의 댓글