어떤 유형의 데이터가 전달되는지 이해 어려움 -> 함수 매개변수와 변수에 아무런 정보가 없음
코드 내에서 전달되는 데이터 유형을 지정할 수 있다. 유형이 일치하지 않을 때 오류 보고 가능
= 코드 실행 전에 지정된 유형이 일치하는지 확인
string = "Hello, TypeScript!";
컴파일러 : npm을 통해 설치 가능
npm install typescript --save-dev
npx tsc로 실행 가능
컴파일러 구성 : npx tsc --init
function greet(name: string): string {
return `Hello ${name}!`;
const message string = greet("world");
1) boolean
let isActive: boolean = true;
let hasPermission = false;
2) number
3) string
let color: string = "blue";
let fullName: string = 'John Doe';
4) bigint
5) symbol : 중복되지 않는 고유한 값
ex. 객체의 속성 이름이 겹치지 않게 하기 위해 주로 사용한다.
const ID = Symbol('id');
const user = { name: 'Alice', [ID]: 123, };
console.log(user[ID]); // 123
1) 명시적 타이핑 : 변수의 유형을 명시적으로 선언한다.
// String
greeting: string = "Hello, TypeScript!";
// Number
userCount: number = 42;
// Boolean
isLoading: boolean = true;
// Array of numbers
scores: number[] = [100, 95, 98];
2) 유형 추론 : TypeScript는 할당된
초기값을 기반으로 변수의 유형을 자동으로 결정(추론)할 수 있다.
let username = "alice"; infers 'string'
let score = 100; // infers 'number'
// TypeScript infers the shape of the object
const user = {
name: "Alice",
age: 30,
isAdmin: true
};
// TypeScript knows these properties exist
console.log(user.name); // OK
console.log(user.email); // Error: Property 'email' does not exist
= JavaScript는 오류 없이 실행되지만 버그가 발생할 가능성이 있다.
function add(a: number, b:number): number {
return a + b;
}
any를 사용하면 TypeScript의 유형 검사가 비활성화된다.
1) JavaScript코드를 TypeScript로 마이그레이션할 때
2) 유형이 알려지지 않은 동적 콘텐츠로 작업할 때
3) 특정 사례에 대한 유형 검사를 거부해야 하는 경우
let v:any = true;
v = "string";
Math.round(v); // any타입으로 선언하면 에러가 발생하지 않는다.
let value: unknown;
value = 123; //ok
value = "hello";
let a: any = 10;
let b: unknown = 10;
a.toFixed(); // ✅ OK (위험함)
b.toFixed(); // ❌ Error — b의 타입을 아직 모름
= API 응답 데이터(JSON) 타입을 아직 모를 때
try/catch로 잡은 에러의 타입을 알 수 없을 때
제너릭 함수의 입력 타입이 명확하지 않을 때
function parseJSON(input: string): unknown {
return JSON.parse(input);
}
const data = parseJSON('{"name": "Alice"}');
// data.name; ❌ 에러 (아직 unknown)
if (typeof data === "object" && data !== null && "name" in data) {
console.log((data as any).name); // ✅ 안전하게 접근
}
function throwError(message: string): never {
throw new Error(message);
}
function greet(name?: string) {
return `Hello, ${name || 'stranger'}`;
}
// Optional property in an interface
interface User {
name: string;
age?: number; // Same as `number | undefined` }
function getPrice(price?: number) {
return price ?? 100; // price가 null/undefined이면 기본값 100
}
console.log(user?.address?.city);
const user = {
name: "Alice",
settings: null
};
const theme = user.settings?.theme ?? "light";
console.log(theme); // "light"
배열을 입력하기 위한 특정 구문
const names: string[] = [];
names.push("Dylan");
readonly 배열이 변경되는 것을 방지
const names: readonly string[] = ["Dylan"]; // push를 할 수 없다.
TypeScript는 값이 있는 경우 배열의 유형을 추론할 수 있다.
각 인덱스의 길이와 유형이 미리 정의된 형식화된 배열이다.
배열의 요소가 알려진 유형의 값이 될 수 있기 때문에 유용하다.
// define our tuple
let ourTuple: [number, boolean, string];
// initialize correctly
ourTuple = [false, 'Coding God was here', 5];
boolean, string이 있더라도 순서가 중요하므로 오류가 발생한다. number
const ourReadonlyTuple: readonly [number, boolean, string] = [5, true, 'The Real Coding God'];
// throws error as it is readonly.
ourReadonlyTuple.push('Coding God took a day off');
명명된 튜플
각 인덱스의 값에 대한 컨텍스트 제공
const graph: [x: number, y: number] = [55.2, 41.3];
튜플 구조 분해
const graph: [number, number] = [55.2, 41.3];
const [x, y] = graph;