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.
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.
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.
// 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)); // μ«μ λ©μλ μμ νκ² μ¬μ©
}
}
// 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
}
}
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."
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."
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
In TypeScript, the any type nullifies all the benefits of static typing. Using any disables type checking, which can lead to runtime errors. Instead, use the unknown type and safely narrow it with type guards, or use Generics. Enable ESLint's @typescript-eslint/no-explicit-any rule so that the entire team avoids using any.
Specifying types everywhere makes code verbose and hard to maintain. Modern languages have excellent type inference, so you may omit types in obvious cases. Define types with a focus on function parameters and return types, public APIs, and complex object structures. It is important to maintain an appropriate balance so that types do not harm code readability.
When migrating an existing JavaScript project to TypeScript, do not try to convert all files at once. Turn off tsconfig's strict option at first, convert files from .js to .ts one by one, and gradually enable stricter type checking. Starting with core business logic and shared utilities is highly effective. Use @ts-ignore or @ts-expect-error comments only as a temporary workaround.