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

如何在TypeScript中为函数的原地解构参数指定类型以避免错误?

How to Type hisObject and Correctly Annotate Destructured Function Params in TypeScript

Let's break this down step by step — your current code has a couple of syntax/type annotation issues that are causing errors. Here's how to fix them:

1. Assign HisType to hisObject

First, you need to explicitly declare hisObject with your HisType to ensure TypeScript recognizes its shape. This is straightforward:

type HisType = { a: string; b: number };

// Explicitly type hisObject as HisType
const hisObject: HisType = { a: "hello", b: 42 };

This tells TypeScript that hisObject must always have a string a and number b property, preventing mismatches later on.

2. Correctly Type Destructured Function Parameters

Your original function syntax for destructuring is invalid because you tried to define types directly inside the destructuring pattern ({ a:string, b:number }). That's not how TypeScript handles type annotations for destructured params. Instead, you need to annotate the entire destructured object with your HisType:

function myFn({ a, b }: HisType = hisObject): void {
  console.log(a, b);
}

Let's break this down clearly:

  • { a, b }: This is the destructuring pattern that pulls the a and b properties from the input object.
  • : HisType: This tells TypeScript the input object must match the HisType shape (enforcing a is a string and b is a number).
  • = hisObject: Sets the default value to your pre-typed hisObject — TypeScript automatically checks that this default matches HisType, so no extra validation is needed here.

If you ever need to type properties inline without reusing HisType (though reusing the type is cleaner for maintainability), you'd write it like this:

function myFn({ a, b }: { a: string; b: number } = hisObject): void {
  console.log(a, b);
}

Sticking with HisType is better, though — if you ever need to update the type (e.g., add a new property), you only have to change it in one place.

Full Working Code

Putting it all together, here's the error-free version:

type HisType = { a: string; b: number };

const hisObject: HisType = { a: "test value", b: 100 };

function myFn({ a, b }: HisType = hisObject): void {
  console.log(a, b);
}

// Test cases
myFn(); // Logs "test value", 100
myFn({ a: "updated", b: 200 }); // Logs "updated", 200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 09:22:27