← العودة إلى المدونة

تحويل JSON إلى TypeScript

تعلم كيفية تحويل JSON إلى واجهات TypeScript. أدوات، تقنيات، وأفضل الممارسات.

Big JSON Team13 دقيقة للقراءةprogramming
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

13 دقيقة قراءة

# تحويل JSON إلى TypeScript

تحويل JSON إلى واجهات TypeScript يوفر type safety ويحسن تجربة التطوير.

لماذا TypeScript؟

الفوائد

  • Type Safety - اكتشاف الأخطاء مبكراً
  • الإكمال التلقائي - IntelliSense
  • التوثيق - أنواع موثقة ذاتياً
  • الصيانة - كود أسهل للصيانة
  • إعادة البناء - refactoring آمن

التحويل الأساسي

مثال بسيط

{

"الاسم": "أحمد",

"العمر": 30,

"نشط": true

}

الواجهة المقابلة

interface User {

الاسم: string;

العمر: number;

نشط: boolean;

}

أدوات التحويل

1. quicktype

عبر الإنترنت:
1. افتح quicktype.io
  • الصق JSON
  • اختر TypeScript
  • انسخ الكود
  • سطر الأوامر:
    # تثبيت
    

    npm install -g quicktype

    # تحويل

    quicktype data.json -o types.ts

    # من URL

    quicktype https://api.example.com/users -o types.ts

    2. json2ts

    عبر الإنترنت:
    1. افتح json2ts.com
    
  • الصق JSON
  • احصل على interfaces
  • كمكتبة:
    import { json2ts } from 'json2ts';
    
    

    const json = '{"الاسم": "أحمد", "العمر": 30}';

    const interfaces = json2ts(json);

    console.log(interfaces);

    3. VS Code Extensions

    JSON to TS:
    1. ثبّت ملحق "JSON to TS"
    
  • انسخ JSON
  • Ctrl+Shift+P
  • "Convert JSON to TypeScript"
  • أنواع البيانات

    الأنواع البسيطة

    interface Example {
    

    // String

    الاسم: string;

    // Number

    العمر: number;

    // Boolean

    نشط: boolean;

    // Null

    القيمة: null;

    // Any

    البيانات: any;

    }

    المصفوفات

    interface User {
    

    // مصفوفة من strings

    المهارات: string[];

    // مصفوفة من أرقام

    الدرجات: number[];

    // مصفوفة من كائنات

    الطلبات: Order[];

    }

    interface Order {

    id: number;

    المبلغ: number;

    }

    الكائنات المتداخلة

    interface User {
    

    الاسم: string;

    العنوان: {

    المدينة: string;

    الشارع: string;

    الرمز: string;

    };

    }

    // أو منفصلة

    interface Address {

    المدينة: string;

    الشارع: string;

    الرمز: string;

    }

    interface User {

    الاسم: string;

    العنوان: Address;

    }

    Optional Properties

    interface User {
    

    // مطلوب

    الاسم: string;

    // اختياري

    الهاتف?: string;

    البريد?: string;

    }

    Union Types

    interface Response {
    

    // قيمة أو null

    البيانات: User | null;

    // عدة أنواع

    القيمة: string | number;

    // قيم محددة

    الحالة: 'نجاح' | 'خطأ' | 'تحميل';

    }

    أمثلة عملية

    API Response

    {
    

    "success": true,

    "data": {

    "users": [

    {

    "id": 1,

    "name": "أحمد",

    "email": "ahmed@example.com",

    "role": "admin"

    }

    ],

    "total": 100

    }

    }

    interface ApiResponse<T> {
    

    success: boolean;

    data: T;

    error?: string;

    }

    interface UsersData {

    users: User[];

    total: number;

    }

    interface User {

    id: number;

    name: string;

    email: string;

    role: 'admin' | 'user' | 'guest';

    }

    // الاستخدام

    type UsersResponse = ApiResponse<UsersData>;

    ملف تكوين

    {
    

    "database": {

    "host": "localhost",

    "port": 5432,

    "name": "mydb"

    },

    "server": {

    "port": 3000,

    "cors": true

    }

    }

    interface Config {
    

    database: DatabaseConfig;

    server: ServerConfig;

    }

    interface DatabaseConfig {

    host: string;

    port: number;

    name: string;

    username?: string;

    password?: string;

    }

    interface ServerConfig {

    port: number;

    cors: boolean;

    timeout?: number;

    }

    التحويل المتقدم

    Generic Types

    interface PaginatedResponse<T> {
    

    data: T[];

    page: number;

    limit: number;

    total: number;

    }

    // الاستخدام

    type UsersList = PaginatedResponse<User>;

    type ProductsList = PaginatedResponse<Product>;

    Utility Types

    interface User {
    

    id: number;

    الاسم: string;

    البريد: string;

    العمر: number;

    }

    // جميع الحقول اختيارية

    type PartialUser = Partial<User>;

    // جميع الحقول مطلوبة

    type RequiredUser = Required<User>;

    // للقراءة فقط

    type ReadonlyUser = Readonly<User>;

    // اختيار حقول محددة

    type UserPreview = Pick<User, 'id' | 'الاسم'>;

    // حذف حقول

    type UserWithoutId = Omit<User, 'id'>;

    Index Signatures

    // كائن بمفاتيح ديناميكية
    

    interface Dictionary {

    [key: string]: string;

    }

    // مثال

    interface UserRoles {

    [userId: number]: string;

    }

    const roles: UserRoles = {

    1: 'admin',

    2: 'user',

    3: 'guest'

    };

    التحويل البرمجي

    دالة بسيطة

    function jsonToInterface(json: any, name: string): string {
    

    const properties = Object.keys(json).map(key => {

    const value = json[key];

    const type = typeof value;

    let tsType: string;

    if (Array.isArray(value)) {

    tsType = 'any[]';

    } else if (type === 'object' && value !== null) {

    tsType = 'object';

    } else {

    tsType = type;

    }

    return ${key}: ${tsType};;

    }).join('\n');

    return interface ${name} {\n${properties}\n};

    }

    // الاستخدام

    const json = {

    الاسم: 'أحمد',

    العمر: 30

    };

    const result = jsonToInterface(json, 'User');

    console.log(result);

    دالة متقدمة

    function generateInterface(
    

    obj: any,

    name: string = 'Root',

    indent: number = 0

    ): string {

    const spaces = ' '.repeat(indent);

    const properties: string[] = [];

    for (const [key, value] of Object.entries(obj)) {

    let type: string;

    if (value === null) {

    type = 'null';

    } else if (Array.isArray(value)) {

    if (value.length > 0 && typeof value[0] === 'object') {

    const itemName = ${name}${key.charAt(0).toUpperCase() + key.slice(1)}Item;

    type = ${itemName}[];

    } else {

    type = 'any[]';

    }

    } else if (typeof value === 'object') {

    const nestedName = ${name}${key.charAt(0).toUpperCase() + key.slice(1)};

    type = nestedName;

    } else {

    type = typeof value;

    }

    properties.push(${spaces} ${key}: ${type};);

    }

    return ${spaces}interface ${name} {\n${properties.join('\n')}\n${spaces}};

    }

    استخدام مع Fetch

    // تعريف الأنواع
    

    interface User {

    id: number;

    name: string;

    email: string;

    }

    interface ApiResponse<T> {

    success: boolean;

    data: T;

    }

    // دالة Fetch مع أنواع

    async function fetchUser(id: number): Promise<User> {

    const response = await fetch(/api/users/${id});

    const data: ApiResponse<User> = await response.json();

    if (!data.success) {

    throw new Error('فشل جلب المستخدم');

    }

    return data.data;

    }

    // الاستخدام

    const user = await fetchUser(1);

    console.log(user.name); // IntelliSense يعمل!

    Type Guards

    interface User {
    

    type: 'user';

    name: string;

    }

    interface Admin {

    type: 'admin';

    name: string;

    permissions: string[];

    }

    type Person = User | Admin;

    // Type guard

    function isAdmin(person: Person): person is Admin {

    return person.type === 'admin';

    }

    // الاستخدام

    function greet(person: Person) {

    if (isAdmin(person)) {

    console.log(Admin: ${person.name});

    console.log(Permissions: ${person.permissions});

    } else {

    console.log(User: ${person.name});

    }

    }

    Zod (Runtime Validation)

    import { z } from 'zod';
    
    

    // تعريف Schema

    const UserSchema = z.object({

    id: z.number(),

    name: z.string(),

    email: z.string().email(),

    age: z.number().min(18).optional()

    });

    // استخراج النوع

    type User = z.infer<typeof UserSchema>;

    // التحقق من البيانات

    const data = {

    id: 1,

    name: 'أحمد',

    email: 'ahmed@example.com'

    };

    const user = UserSchema.parse(data);

    // user الآن من نوع User

    أفضل الممارسات

    1. أسماء واضحة

    // جيد
    

    interface UserProfile {

    name: string;

    email: string;

    }

    // سيء

    interface UP {

    n: string;

    e: string;

    }

    2. فصل الأنواع

    // types/user.ts
    

    export interface User {

    id: number;

    name: string;

    }

    // types/api.ts

    export interface ApiResponse<T> {

    data: T;

    }

    // استخدام

    import { User } from './types/user';

    import { ApiResponse } from './types/api';

    3. استخدم Readonly عند الحاجة

    interface Config {
    

    readonly apiUrl: string;

    readonly timeout: number;

    }

    const config: Config = {

    apiUrl: 'https://api.example.com',

    timeout: 5000

    };

    // خطأ: لا يمكن التعديل

    // config.apiUrl = 'new-url';

    4. وثق الأنواع

    /*
    

    معلومات المستخدم

    /

    interface User {

    / معرف فريد للمستخدم /

    id: number;

    /* الاسم الكامل /

    name: string;

    /* البريد الإلكتروني (اختياري) /

    email?: string;

    }

    مقارنة الأدوات

    quicktype

    • ✅ قوي جداً
    • ✅ يدعم لغات متعددة
    • ✅ CLI و Web
    • ❌ قد يكون معقداً

    json2ts

    • ✅ بسيط وسريع
    • ✅ واجهة ويب سهلة
    • ❌ ميزات أقل

    VS Code Extension

    • ✅ مدمج في المحرر
    • ✅ سريع
    • ❌ ميزات أساسية فقط

    الملخص

    تحويل JSON إلى TypeScript:

    • يحسن type safety
    • يسهل التطوير
    • أدوات كثيرة متاحة
    • أفضل ممارسات مهمة

    استخدم TypeScript لكود أكثر أماناً!

    Share:

    مقالات ذات صلة

    Read in English