
Objects as Parameters in TypeScript
Objects as Parameters in TypeScript 관련
In TypeScript, functions can accept objects as parameters. This is particularly useful when dealing with multiple related values.
Using Objects with Specific Properties
Here's a function that takes an object with an id
property and returns a new object:
function createEmployee({ id }: { id: number }): { id: number; isActive: boolean } {
return { id, isActive: id % 2 === 0 };
}
const firstEmployee = createEmployee({ id: 1 });
console.log(firstEmployee); // { id: 1, isActive: false }
const secondEmployee = createEmployee({ id: 2 });
console.log(secondEmployee); // { id: 2, isActive: true }
The function createEmployee
:
- Takes an object with a single property,
id
, as a parameter. - Returns a new object with two properties:
id
andisActive
.
The isActive
property is determined by checking if the id
is even (id % 2 === 0
).
Destructuring is used in the parameter:
{ id }
extracts theid
property from the input object directly.
Accepting More Complex Objects
Now, let’s look at a function that takes an object with multiple properties:
function createStudent(student: { id: number; name: string }): void {
console.log(`Welcome to the course, ${student.name}!`);
}
const newStudent = { id: 1, name: "John" };
createStudent(newStudent); // "Welcome to the course, John!"
The function createStudent
:
- Accepts an object with two properties:
id
andname
. - Logs a welcome message using the
name
property.
The newStudent
object matches the structure expected by the function, so it’s passed directly.
Why Use Objects as Parameters?
First of all, functions with objects as parameters are easier to read, especially when dealing with multiple related values. Also, using destructuring you can extract only the needed properties from an object, making the code more concise. And finally, objects can be reused across functions without creating new ones every time.
Excess Property Checks in TypeScript
In TypeScript, excess property checks help ensure that objects passed to functions only contain properties defined in the function’s parameter type. If there are extra properties, TypeScript will raise an error. Let's see how this works with simple examples.
1. Extra Property Error
Here’s a function that accepts an object with id
and name
, but no extra properties:
function createStudent(student: { id: number; name: string }): void {
console.log(`Welcome, ${student.name}!`);
}
const newStudent = { id: 1, name: "John", age: 20 }; // Extra property 'age'
createStudent(newStudent); // Error: 'age' is not expected
TypeScript gives an error because the age
property is not part of the expected object structure.
2. Fixing the Error
To avoid the error, just remove any extra properties:
const validStudent = { id: 1, name: "John" };
createStudent(validStudent); // This works fine
This works because the object only has the expected properties: id
and name
.
3. Using Type Assertion (Not Recommended)
If you really need to pass an object with extra properties, you can use type assertion to tell TypeScript to ignore the extra properties:
const studentWithExtras = { id: 1, name: "John", age: 20 };
createStudent(studentWithExtras as { id: number; name: string }); // Bypasses the error
While this works, it’s better to match the expected structure instead of using type assertion.
- TypeScript expects objects to match the exact shape of the parameter type.
- Excess properties cause errors to ensure the structure is correct.
- Fix the object or use type assertion (carefully) if you need extra properties.
Excess property checks help keep your code safe and ensure only the right data is passed to functions.