TypeScript中如何判断变量是接口或接口数组并完成格式转换?
Hey there! Let's tackle this TypeScript problem you're working on. The core task is to take a List (where the people property might be a single Person or an array of Persons) and convert it into an OfficialList where people is always an array. Here's how to do it cleanly:
First, let's align our interfaces with standard TypeScript naming conventions (uppercase for interface names) and define a sample Person interface since it's referenced:
// Define your Person interface (adjust properties to match your actual use case) interface Person { name: string; // Add other properties like age, id, etc. as needed } interface List { people: Person | Person[]; } interface OfficialList { people: Person[]; }
Option 1: Use Array.isArray (Simplest Approach)
TypeScript recognizes Array.isArray as a built-in type guard, so it automatically narrows down the type of list.people after the check. This is the most straightforward and readable solution:
function toOfficialList(list: List): OfficialList { // Check if people is already an array; if not, wrap it in a new array const normalizedPeople = Array.isArray(list.people) ? list.people : [list.people]; return { people: normalizedPeople }; }
Option 2: Custom Type Guard (For Reusable/Complex Checks)
If you ever need more validation beyond just checking array type, you can create a custom type guard function. This makes the logic explicit and reusable across your codebase:
// Custom type guard to confirm a value is a Person array function isPersonArray(people: Person | Person[]): people is Person[] { return Array.isArray(people); } function toOfficialList(list: List): OfficialList { const normalizedPeople = isPersonArray(list.people) ? list.people : [list.people]; return { people: normalizedPeople }; }
Test the Function
Let's verify this works for both scenarios:
// Test with a single Person const singlePersonInput: List = { people: { name: "Raj" } }; const officialSingle = toOfficialList(singlePersonInput); // officialSingle.people will be [{ name: "Raj" }] // Test with a Person array const arrayInput: List = { people: [{ name: "Raj" }, { name: "Alice" }] }; const officialArray = toOfficialList(arrayInput); // officialArray.people stays the original array: [{ name: "Raj" }, { name: "Alice" }]
This approach keeps type safety intact—TypeScript won't throw any type errors because it understands the type narrowing from our checks.
内容的提问来源于stack exchange,提问作者programmerRaj

