javascript
JS와 TS에서 사용되는 typeof는 쓰임이 다르다
TypeScript & JavaScript에서 typeof 차이점 정리
typeof는 값의 타입을 확인하거나 타입을 추출할 때 사용하는 키워드입니다.
하지만 JS와 TS에서 쓰임이 조금 다릅니다
즉 같은 키워드를 JS와 TS에서 사용중이지만 결과가 다름
( 특히 객체가 다름.. )
js의 경우 typeof {a:'1'} 결과는 "object"
ts의 경우 typeof {a:'1'} 결과는 {a:string}
참고로 typeof { a: '1' } as const 의 결과는 {a:'1'}
1️⃣ JavaScript – 값의 타입 확인
JS에서는 typeof가 값의 타입을 문자열로 알려줍니다.
// 기본 타입
typeof 123 // "number"
typeof "hello" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof Symbol() // "symbol"
typeof 10n // "bigint"
// 객체 & 함수
typeof {} // "object"
typeof [] // "object" (배열도 객체)
typeof null // "object" (역사적 버그)
typeof function(){} // "function"
// 브라우저 객체
typeof window // "object"
typeof document // "object"
💡 포인트: 객체(배열, null, window 등)와 일반 객체 모두 "object"로 나옵니다.
2️⃣ TypeScript – 값에서 타입 추출
TS에서는 typeof를 값의 타입을 그대로 추출할 때 사용합니다.
// 객체 타입 추출
const user = { name: "Tom", age: 20 };
type User = typeof user;
// User === { name: string; age: number }
// 배열 타입 추출
const numbers = [1, 2, 3];
type Numbers = typeof numbers;
// Numbers === number[]
// 함수 타입 추출
function greet() {
console.log("Hi");
}
type Greet = typeof greet;
// Greet === () => void
// 중첩 객체 타입 추출
const obj = { a: 1, b: { c: 2 } };
type ObjType = typeof obj;
// ObjType === { a: number; b: { c: number } }
💡 포인트: TS에서는 객체, 배열, 함수 등 값의 구조를 그대로 타입으로 가져올 수 있음
✅ 요약
구분 사용법 설명
JS typeof 값 값의 타입 문자열 반환 ("number", "object" 등)
TS type T = typeof 값 값의 구조를 그대로 타입으로 추출