In TypeScript, type checking is automatically performed and is one of the core features of the language. When you define an interface, TypeScript performs type checking at compile time to ensure you adhere to the structure defined by the interface.
For example, suppose we have the following interface:
typescriptinterface IUser { name: string; age: number; isActive: boolean; }
When you attempt to create an object of type IUser, the TypeScript compiler automatically checks if the object matches the IUser interface. For instance:
typescriptlet user: IUser = { name: 'Alice', age: 30, isActive: true };
In this example, the user object adheres to the structure of IUser, so it compiles successfully. However, if you attempt to add a property not defined in the interface or omit a property, the TypeScript compiler will throw an error:
typescriptlet user: IUser = { name: 'Bob', // 'age' property missing will cause a compilation error isActive: true };
This will produce an error similar to the following:
shellProperty 'age' is missing in type '{ name: string; isActive: boolean; }' but required in type 'IUser'.
Additionally, you can use interfaces for type checking within functions. For example:
typescriptfunction greetUser(user: IUser) { console.log(`Hello, ${user.name}!`); } // Correct usage greetUser({ name: 'Charlie', age: 25, isActive: false }); // Missing other properties will cause an error greetUser({ name: 'Dave' });
For the function greetUser, the parameters passed when calling it must conform to the structure of the IUser interface; otherwise, the TypeScript compiler will report an error.
In summary, in TypeScript, interface type checking is static and occurs at compile time, not at runtime. The compiler checks the structure and types in the code based on the interface you define, ensuring the correctness and consistency of types. This feature is particularly useful in large projects as it can identify potential errors and issues early on.