如何在TypeScript中为函数的原地解构参数指定类型以避免错误?
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 theaandbproperties from the input object.: HisType: This tells TypeScript the input object must match theHisTypeshape (enforcingais a string andbis a number).= hisObject: Sets the default value to your pre-typedhisObject— TypeScript automatically checks that this default matchesHisType, so no extra validation is needed here.
Alternative: Type Individual Properties Directly (Less Recommended)
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

