What & Why Typescript & Basic

gyojinnK·2024년 1월 23일

리액트 플러스

목록 보기
6/11
post-thumbnail

타입스크립트는 자바스크립트의 확장 문법

  1. 정적 타입
  2. 컴파일 에러 예방
  3. 손쉬운 디버깅
  • 실제 연구에 따르면 Javascript 버그의 15%가 사전에 Typescript로 감지할 수 있다고 함
  1. 가독성 및 생산성 향상
  • 함수 매개변수 등 어떠한 변수에 타입이 기입되어 있기 때문에 가동성 및 협업 환경에서도 이점이 있음

사용 방법

// Primitives: number, string, boolean
// More complex types: arrays, object
// Function types, parameters

//Primitives
let age: number;

age = 12.1;


let userName: string;

userName = 'Max'

let isInstructor: boolean;

isInstructor = true;


// More complex types
let hobbies: string[];

hobbies = ['Sports', 'Cooking']

let person: {
    name: string;
    age: number;
};

person = {
    name: 'Max',
    age: 27,
}

// person = {
//     isEmployee: true
// }

let people: {
    name: string;
    age: number;
}[];


// Type inference
let course = "React - The Complete Guide";

// type inference (타입 추론)
// 명시적인 타입 표기가 없더라도 이전의 선언과 초기화로 타입을 유추
// course = 12341; // error


// Union type
let lecture: string | number = "React - The Complete Guide";
lecture = 12341;

// type alias
type Animal = {
    name: string;
    age: number;
};

let cat: Animal;
let dog: Animal;


// Function & types
//                                : return type
function add(a: number, b: number): number {
    return a + b;
}
// 함수 리턴 타입을 지정하지 않아도 타입 추론이 이루어짐

//                               : no return type
function printOfValue(value: any): void {
    console.log(value);
}


// Generics
function insertAtBeginning<T>(array: T[], value: T){
    const newArray = [value, ...array];
    return newArray;
}
// T를 사용해서 any가 아니라는 것을 알려줌
// 이후 추론을 통해 타입을 알아냄
// 즉, 원하는 타입으로 해당 함수를 실행하고 나면
// 해당 타입으로 고정되어 동작!!!
// Generics는 유연성과 타입 안정성 측면에서 매우 유용

const demoArray = [1, 2, 3];

const updatedArray = insertAtBeginning(demoArray, -1);  // [-1, 1, 2, 3]
const stringArray = insertAtBeginning(['a','b','c'], 'd')

// updatedArray[0].split('');
profile
기록하고 꺼내보고

0개의 댓글