DevToolBox무료
블로그

JSON에서 TypeScript로: 예제와 함께하는 완벽 가이드

12분 읽기by DevToolBox

Converting JSON to TypeScript interfaces is one of the most common tasks in modern web development. Whether you're consuming REST APIs, working with configuration files, or defining data models, having proper TypeScript types ensures type safety and better developer experience.

Convert JSON to TypeScript instantly with our free tool →

Why Convert JSON to TypeScript?

TypeScript's type system catches errors at compile time that would otherwise surface at runtime. When you receive JSON from an API, TypeScript has no idea what shape that data takes — unless you define interfaces. Without types, you lose autocompletion, refactoring support, and compile-time error checking.

  • Autocompletion — your editor suggests valid property names
  • Compile-time errors — catch typos and missing fields before deployment
  • Self-documenting code — interfaces describe your data shape
  • Refactoring safety — rename a field and TypeScript finds every usage

Basic Conversion Rules

The fundamental mappings from JSON types to TypeScript types are straightforward:

JSON TypeTypeScript TypeExample
stringstring"hello"
number (int)number42
number (float)number3.14
booleanbooleantrue
nullnullnull
arrayT[][1, 2, 3]
objectinterface{"key": "val"}
// JSON
{
  "name": "Alice",
  "age": 30,
  "active": true
}

// TypeScript
interface User {
  name: string;
  age: number;
  active: boolean;
}

Handling Nested Objects

Real-world JSON is rarely flat. When objects contain other objects, you should create separate interfaces for each level:

// JSON
{
  "id": 1,
  "name": "Alice",
  "address": {
    "street": "123 Main St",
    "city": "Springfield",
    "coordinates": {
      "lat": 39.7817,
      "lng": -89.6501
    }
  }
}

// TypeScript
interface Coordinates {
  lat: number;
  lng: number;
}

interface Address {
  street: string;
  city: string;
  coordinates: Coordinates;
}

interface User {
  id: number;
  name: string;
  address: Address;
}

Tip: Use separate interfaces rather than deeply nested inline types. It makes your code more readable and reusable.

Array Types

Arrays in JSON can contain uniform or mixed types. TypeScript handles both cases:

// Uniform array
{ "tags": ["typescript", "react", "next"] }
// -> tags: string[]

// Array of objects
{
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ]
}
// -> users: User[]

// Mixed array (rare but possible)
{ "data": [1, "two", true] }
// -> data: (number | string | boolean)[]

When an array contains objects of the same shape, define a dedicated interface. For heterogeneous arrays, use union types.

Null and Optional Fields

JSON APIs often return null for missing values, or omit fields entirely. TypeScript distinguishes between these two cases:

// JSON with null values
{
  "id": 1,
  "name": "Alice",
  "avatar": null,
  "bio": null
}

// TypeScript — nullable vs optional
interface User {
  id: number;
  name: string;
  avatar: string | null;    // field exists, value can be null
  bio?: string;              // field might not exist at all
  nickname?: string | null;  // might not exist OR might be null
}

Key difference: null means the field exists but has no value. undefined (optional with ?) means the field might not be present at all. Use | null for nullable fields and ? for optional fields.

Best Practices

  • Use interface over type for object shapes — interfaces are extendable and produce better error messages
  • Prefer readonly for data from APIs that you don't intend to mutate
  • Use unknown instead of any for truly dynamic fields — it forces you to validate before use
  • Name interfaces clearly — use User, not IUser or UserInterface
  • Export shared interfaces in a central types/ directory for reuse across your project
  • Validate at runtime — TypeScript types disappear at runtime, so use libraries like Zod or io-ts for API boundary validation
// Good: runtime validation with Zod
import { z } from 'zod';

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
  avatar: z.string().nullable(),
});

type User = z.infer<typeof UserSchema>;

// Validate API response
const user = UserSchema.parse(await res.json());

Automate the Conversion

Manually writing interfaces for large JSON payloads is tedious and error-prone. Use our JSON to TypeScript converter to instantly generate accurate interfaces from any JSON input. Paste your JSON, get TypeScript — it's that simple.

Try the JSON to TypeScript converter now →

𝕏 Twitterin LinkedIn
도움이 되었나요?

최신 소식 받기

주간 개발 팁과 새 도구 알림을 받으세요.

스팸 없음. 언제든 구독 해지 가능.

Try These Related Tools

TSJSON to TypeScript{ }JSON FormatterGoJSON to Go StructZDJSON to Zod Schema

Related Articles

JSON에서 Go Struct로: 매핑 전략과 모범 사례

JSON에서 Go struct로의 변환을 마스터하세요. struct 태그, 중첩 타입, omitempty, 커스텀 마샬링, 실전 패턴을 다룹니다.

TypeScript vs JavaScript: 언제, 어떻게 변환할까

TypeScript를 JavaScript로, 또는 그 반대로 변환해야 할 시기에 대한 실전 가이드. 마이그레이션 전략, 도구, 번들 크기 영향, 팀 고려사항을 다룹니다.

JSON Schema 유효성 검사: 타입, 도구, 모범 사례

JSON Schema 유효성 검사의 모든 것: 기본 타입부터 고급 패턴, 검증 라이브러리, TypeScript 및 API 통합까지.

JSON to Java 클래스 변환기: POJO, Jackson, Gson, Lombok 가이드

JSON을 Java 클래스로 온라인 변환. Jackson, Gson, Lombok으로 POJO 생성 방법을 코드 예제와 함께 알아보세요.

JSON to Zod Schema: TypeScript 타입 안전 런타임 유효성 검사

JSON을 Zod 스키마로 변환하여 TypeScript에서 타입 안전한 런타임 유효성 검사를 구현하는 방법을 알아보세요.