πŸ’» Programming

Static Typing

Static Typing

A programming approach that performs type checking at compile time. Used in TypeScript, Java, Rust, and others, with strengths in bug prevention and IDE support.

πŸ“– Detailed Explanation

Static Typing is a programming approach in which the types of variables, function parameters, and return values are checked at compile time (before the code runs). Before the program is executed, the compiler can detect type mismatches and thereby find errors in advance. Java, C++, Rust, TypeScript, Go, and Kotlin are representative languages that support static typing. By giving the code an explicit contract such as "this variable can only ever hold a number," static typing increases the stability and predictability of a program.

In the comparison with Dynamic Typing, the biggest difference is when type checking takes place. Dynamically typed languages such as JavaScript, Python, and Ruby check types at runtime (during execution), so type errors cannot be found until the code is actually run. Static typing, by contrast, detects errors immediately at the code-writing stage. Dynamic typing has advantages in rapid prototyping and flexibility, while static typing shows strengths in the stability and maintainability of large codebases. Recently, the trend of adding a static type system to dynamic languages, as TypeScript does, has become prominent.

Type Inference is a core feature of modern statically typed languages. In TypeScript, Kotlin, Swift, Rust, and others, the compiler automatically infers types from context, even when developers do not specify every type explicitly. For example, if you write let count = 10, the compiler infers count as the number type. This makes it possible to write concise code like in dynamic languages while maintaining the safety of static typing. Type inference improves code readability and reduces redundancy, but in complex situations, explicit type declarations help readability.

The practical benefits fall into three main categories. First, bug prevention: common runtime errors such as null references and type mismatches are blocked at compile time. Second, stronger IDE support: autocompletion, refactoring tools, and type-based search become more accurate, which improves development productivity. Third, safe refactoring: when a function signature or data structure is changed, the compiler points out all affected code, making large-scale code changes safe. Especially in projects where multiple developers collaborate, types act as a contract for the code and reduce communication costs.

πŸ’» Code Example

static-typing.ts - TypeScript type declarations
// TypeScript 정적 타이핑 예제

// 1. κΈ°λ³Έ νƒ€μž… μ„ μ–Έ
let username: string = "홍길동";
let age: number = 25;
let isActive: boolean = true;

// νƒ€μž… 뢈일치 - 컴파일 μ—λŸ¬!
// username = 123;  // Error: Type 'number' is not assignable to type 'string'

// 2. μΈν„°νŽ˜μ΄μŠ€λ‘œ 객체 νƒ€μž… μ •μ˜
interface User {
    id: number;
    name: string;
    email: string;
    role: 'admin' | 'user' | 'guest';  // μœ λ‹ˆμ˜¨ νƒ€μž…
    createdAt?: Date;  // 선택적 ν”„λ‘œνΌν‹°
}

// 3. ν•¨μˆ˜ νƒ€μž… μ„ μ–Έ
function createUser(name: string, email: string): User {
    return {
        id: Date.now(),
        name,
        email,
        role: 'user'
    };
}

// 4. νƒ€μž… μΆ”λ‘  - νƒ€μž… λͺ…μ‹œ 없이도 νƒ€μž… μ•ˆμ „
const numbers = [1, 2, 3];  // number[]둜 μΆ”λ‘ 
const doubled = numbers.map(n => n * 2);  // number[]둜 μΆ”λ‘ 

// 5. μ œλ„€λ¦­μ„ ν™œμš©ν•œ μž¬μ‚¬μš© κ°€λŠ₯ν•œ νƒ€μž…
interface ApiResponse<T> {
    data: T;
    status: number;
    message: string;
}

async function fetchUser(id: number): Promise<ApiResponse<User>> {
    const response = await fetch(`/api/users/${id}`);
    return response.json();
}

// 6. νƒ€μž… κ°€λ“œλ‘œ λŸ°νƒ€μž„ μ•ˆμ „μ„± 확보
function processValue(value: string | number): void {
    if (typeof value === 'string') {
        console.log(value.toUpperCase());  // λ¬Έμžμ—΄ λ©”μ„œλ“œ μ•ˆμ „ν•˜κ²Œ μ‚¬μš©
    } else {
        console.log(value.toFixed(2));  // 숫자 λ©”μ„œλ“œ μ•ˆμ „ν•˜κ²Œ μ‚¬μš©
    }
}
StaticTyping.java - Java type declarations
// Java 정적 타이핑 예제

public class StaticTyping {

    // 1. 클래슀둜 νƒ€μž… μ •μ˜
    public class User {
        private final Long id;
        private String name;
        private String email;
        private UserRole role;

        public User(Long id, String name, String email) {
            this.id = id;
            this.name = name;
            this.email = email;
            this.role = UserRole.USER;
        }

        // Getter/Setter - νƒ€μž… μ•ˆμ „ν•œ μ ‘κ·Ό
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
    }

    // 2. Enum으둜 μ œν•œλœ κ°’ μ •μ˜
    public enum UserRole {
        ADMIN, USER, GUEST
    }

    // 3. μ œλ„€λ¦­μœΌλ‘œ νƒ€μž… μ•ˆμ „ν•œ μ»¬λ ‰μ…˜
    public List<User> findActiveUsers(List<User> users) {
        return users.stream()
            .filter(user -> user.getRole() != UserRole.GUEST)
            .collect(Collectors.toList());
    }

    // 4. Java 17+ λ ˆμ½”λ“œ - λΆˆλ³€ 데이터 클래슀
    public record ApiResponse<T>(
        T data,
        int status,
        String message
    ) {}

    // 5. νƒ€μž… μ•ˆμ „ν•œ λ©”μ„œλ“œ - 잘λͺ»λœ νƒ€μž…μ€ 컴파일 μ—λŸ¬
    public void processUser(User user) {
        // user.getName() 은 ν™•μ‹€νžˆ String λ°˜ν™˜
        String upperName = user.getName().toUpperCase();
        System.out.println(upperName);
    }

    public static void main(String[] args) {
        // 컴파일 νƒ€μž„ νƒ€μž… 체크
        String name = "홍길동";
        int age = 25;

        // name = 123;  // 컴파일 μ—λŸ¬: incompatible types
        // age = "25";  // 컴파일 μ—λŸ¬: incompatible types
    }
}

πŸ—£οΈ Conversation Examples from Practice

Technical Meeting Migrating from JavaScript to TypeScript

Tech Lead:

"This quarter, we're planning to migrate our frontend code to TypeScript. Type-related bugs keep occurring at runtime."

Frontend Developer:

"I agree. Just last week, an undefined error went out to production because the API response structure changed. With static typing, it would have been caught at the compile stage."

Junior Developer:

"Wouldn't defining types take a lot of effort? It seems like the amount of code would increase..."

Tech Lead:

"It may feel that way at first. But TypeScript has good type inference, so you don't need to write types everywhere. Also, VSCode autocompletion gets much better, and when refactoring you can immediately see which code is affected, so development actually gets faster."

Frontend Developer:

"I'd like us to adopt it gradually. We start with strict mode turned off in tsconfig, convert files to .ts one by one, and turn strict mode on later."

Tech Lead:

"Sounds good. Let's auto-generate the API response types from the OpenAPI spec and start adding types from the common utility functions. And let's avoid any as much as possible."

Technical Interview Static Typing vs. Dynamic Typing

Interviewer:

"Please explain the differences between static typing and dynamic typing, and the pros and cons of each."

Candidate:

"Static typing checks types at compile time, and dynamic typing checks them at runtime. With static typing, as in TypeScript and Java, a variable's type is determined at the time the code is written, and if there is a type mismatch, an error occurs before the program runs."

Interviewer:

"Then in which situations would you choose which typing approach?"

Candidate:

"I prefer static typing for large team projects, projects that require long-term maintenance, and cases with complex business logic. This is because types serve as documentation, and better IDE support increases collaboration efficiency. On the other hand, dynamic typing can be faster for rapid prototyping or writing scripts."

Interviewer:

"What do you think about the any type in TypeScript?"

Candidate:

"any neutralizes the benefits of static typing, so it should be avoided whenever possible. Use it only temporarily during migration or when you truly need to allow every type; usually it is better to use the unknown type and narrow it down with type guards. Turning on ESLint's no-explicit-any rule is also a good approach."

Code Review Suggestion for Improving Type Definitions

Reviewer:

"The return type isn't specified in this function. Since it returns a complex object, relying only on type inference could lead to mistakes when refactoring later. Please write the return type explicitly."

Developer:

"Understood. Also, how about generating this API response type automatically from a Zod schema? With z.infer, you can do runtime validation and type definition at the same time, so it reduces duplication and becomes safer."

Reviewer:

"Good idea. We don't know what will come in at runtime from an external API response, so validating with Zod is right. By the way, please change the part where you used an as assertion to a type guard. as bypasses the type system, so there is a possibility of runtime errors."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More