You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript入门:定义含n个键值对的对象及指定JSON的接口

TypeScript Newbie Questions: Object Definitions & JSON Interfaces

Hey there! As someone who’s navigated the TypeScript learning curve, I’ll walk you through these two questions clearly and practically—no overly technical jargon, just straightforward explanations.


1. Defining an object with n key-value pairs in TypeScript

If you need an object that can hold any number of key-value pairs, you’ve got two flexible, go-to options:

Option 1: Index Signatures

Index signatures let you define a pattern for your object’s keys and values. For example, if your keys are strings and values can be any type:

interface FlexibleObject {
  [key: string]: any; // Keys are strings, values can be anything
}

// Usage example
const myObj: FlexibleObject = {
  name: "Alice",
  age: 30,
  isStudent: false
};

Want to enforce a specific value type (like all strings)? Just tweak the signature:

interface StringOnlyObject {
  [key: string]: string;
}

const contactInfo: StringOnlyObject = {
  email: "alice@example.com",
  address: "123 Main St"
};

Option 2: The Record Utility Type

TypeScript’s built-in Record type is a clean shorthand for this scenario. It takes two generic parameters: the type of your keys, and the type of your values. Syntax: Record<KeyType, ValueType>

// Object with string keys and number values
type ScoreRecord = Record<string, number>;

const examScores: ScoreRecord = {
  math: 95,
  science: 88,
  history: 92
};

// Bonus: Restrict keys to a specific set of strings
type Fruit = "apple" | "banana" | "orange";
type FruitPriceMap = Record<Fruit, number>;

const fruitPrices: FruitPriceMap = {
  apple: 1.99,
  banana: 0.99,
  orange: 1.49
};

2. Creating TypeScript interfaces for your JSON structure

Let’s break down your JSON layer by layer, starting from the innermost objects and working our way up to the root:

Step 1: Define the innermost product items

The asian and american objects have arbitrary string keys and string values—we’ll use an index signature here:

interface ProductDetails {
  [key: string]: string;
}

Step 2: Define product categories per branch

Each branch (like NYC or Boston) has asian and american product groups:

interface BranchProducts {
  asian: ProductDetails;
  american: ProductDetails;
}

Step 3: Define a single branch structure

Every branch contains a products object with the categories above:

interface Branch {
  products: BranchProducts;
}

Step 4: Define the top-level company interface

The root object has basic company info plus a branch object (with arbitrary string keys like "nyc" or "boston") pointing to Branch objects:

interface CompanyProfile {
  company: string;
  logoUrl: string;
  phone: string;
  branch: Record<string, Branch>;
}

Full example usage

Now you can type your JSON data with this interface to get TypeScript’s type checking benefits:

const companyData: CompanyProfile = {
  "company": "abc inc",
  "logoUrl": "someUrl",
  "phone": "1234567890",
  "branch": {
    "nyc": {
      "products": {
        "asian": {
          "somekey1": "someValue1",
          "somekey2": "someValue2",
          "somekeyN": "somevalueN"
        },
        "american": {
          "somekey1": "someValue1",
          "somekey2": "someValue2",
          "somekeyN": "somevalueN"
        }
      }
    },
    "boston": {
      "products": {
        "asian": {
          "somekey1": "somevalue1",
          "somekey2": "somevalue2",
          "somekeyN": "somevalueN"
        },
        "american": {
          "somekey1": "..."
        }
      }
    }
  }
};

内容的提问来源于stack exchange,提问作者Aniks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:08:02