💻 Programming

Type

Type

A system for classifying kinds of data. Static/dynamic typing and strong/weak type systems improve code stability and readability and prevent bugs.

📖 Detailed Explanation

A type is a system in programming that classifies and defines kinds of data. By specifying the set of values a variable or expression can hold and the operations applicable to those values, it guides the compiler or interpreter to process data correctly. A type system is a core foundation that ensures the logical consistency of a program.

A primitive type is the most basic form of data provided by a language, such as number, string, boolean, null, and undefined. A composite type is a structure, array, object, or function type built by combining primitive types. In TypeScript, you can use interface, type alias, union, intersection, and similar features to express complex domain models with precision.

Type systems are broadly classified along two axes. First, static vs. dynamic typing is a difference in when type checking occurs. TypeScript and Java check types at compile time, while Python and JavaScript check them at runtime. Second, strong vs. weak typing indicates the strictness of type conversion. Python is strongly typed and does not allow implicit type conversion, while JavaScript is weakly typed and performs automatic type conversion.

In practice, a type system provides three core benefits. First, preventing bugs at compile time blocks runtime errors in advance. Second, the code itself becomes documentation, clearly conveying a function's inputs and outputs. Third, IDE autocompletion and refactoring support increase development productivity. This is why adopting TypeScript has become the standard in large team projects.

💻 Code Example

// TypeScript 타입 정의 종합 예제

// 1. 기본 타입 (Primitive Types)
const userName: string = "홍길동";
const userAge: number = 28;
const isActive: boolean = true;
const nothing: null = null;
const notDefined: undefined = undefined;

// 2. 배열과 튜플
const scores: number[] = [95, 87, 92];
const tuple: [string, number] = ["서울", 37.5665]; // 고정 길이, 고정 타입

// 3. 객체 타입 정의 - Interface
interface User {
    id: number;
    name: string;
    email: string;
    role: "admin" | "user" | "guest"; // 리터럴 타입
    createdAt: Date;
    profile?: {                        // 선택적 속성
        bio: string;
        avatar: string;
    };
}

// 4. Type Alias와 Union Type
type ID = string | number;
type Status = "pending" | "approved" | "rejected";

type ApiResponse = {
    success: boolean;
    data: T;
    error?: string;
    timestamp: number;
};

// 5. 함수 타입 정의
function createUser(
    name: string,
    email: string,
    role: User["role"] = "user"  // Index Access Type
): User {
    return {
        id: Date.now(),
        name,
        email,
        role,
        createdAt: new Date()
    };
}

// 6. 제네릭 타입 활용
function fetchData(url: string): Promise> {
    return fetch(url)
        .then(res => res.json())
        .then(data => ({
            success: true,
            data: data as T,
            timestamp: Date.now()
        }));
}

// 7. 타입 가드 (Type Guard)
function isUser(obj: unknown): obj is User {
    return (
        typeof obj === "object" &&
        obj !== null &&
        "id" in obj &&
        "name" in obj &&
        "email" in obj
    );
}

// 8. 조건부 타입 (Conditional Type)
type NonNullable = T extends null | undefined ? never : T;
type ExtractArrayType = T extends (infer U)[] ? U : never;

// 사용 예시
const users: User[] = [createUser("Alice", "alice@example.com", "admin")];
const result: ExtractArrayType = users[0]; // User 타입

📊 Type System Comparison by Language

Language Checking Time Type Strength Features
TypeScript Static (compile-time) Strong typing Structural typing, gradual adoption possible
Java Static (compile-time) Strong typing Nominal typing, class-based
Python Dynamic (runtime) Strong typing Duck typing, Type Hints supported
JavaScript Dynamic (runtime) Weak typing Implicit type conversion occurs
Rust Static (compile-time) Strong typing Ownership system, zero-cost abstractions
Go Static (compile-time) Strong typing Interface-based polymorphism

💡 Practical Tip: Migrating a JavaScript project to TypeScript can reduce bugs by more than 40%. For Python, use mypy and Type Hints.

🗣️ Examples of Practical Conversations

Code Review: Discussing Type Design

"You shouldn't use any for this API response. Please define it precisely with an interface based on the backend spec. If the fields change later, TypeScript will tell you every place they're used. If you use any, it will blow up at runtime."

Code Review: Using Type Guards

"For data received as unknown, please create a type guard function to validate it. You can combine the 'in' operator with typeof. It's safer than an assertion, and guard functions are reusable too, so it would be good to collect them in utils."

Technical Interview: Asked to Explain the Type System

"Static typing checks types at compile time, so it catches bugs before deployment, while dynamic typing checks at runtime, so it's flexible but test coverage matters. TypeScript layers static types on top of JavaScript, taking the advantages of both worlds."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Beware of Type Coercion

JavaScript's == and + operators perform implicit type conversion. "5" + 3 becomes "53", and "5" - 3 becomes 2. Always use ===, and explicit conversions such as Number() and String() are recommended.

2
Do Not Overuse the any Type

any completely bypasses type checking. It is easy to reach for when in a hurry, but it undermines type safety across the entire codebase. At the very least, use unknown and narrow it with type guards. Turn on ESLint's no-explicit-any rule.

3
Using Type Guards

External data (API responses, user input) has no type guarantee at runtime. Secure data integrity with type guards using the typeof, instanceof, and in operators, or with a runtime validation library such as Zod.

🔗 Related Terms

📚 Learn More