I want to show two seemingly identical situations, but they behave differently
1)
type User = { name: string, age: number };
const user1 = { name: 'Harry', age: 21, skills: 'backend', isAdmin: true }
const user2: User = user1; // NO ERROR
In this situation, TypeScript allows you to add additional properties to the object
2)
type User = { name: string, age: number };
const user2: User = { name: 'Alex', age: 23, skills: 'frontend' } // ERROR!
And in this case we will see an error, although the situations are quite similar
With this in mind, I have 2 questions:
1) How to explain the difference in the behaviors above?
2) How do I declare a type that will cause the object to AT LEAST have all the necessary properties from the User type, and the rest of the properties can be completely different?
CodePudding user response:
For the second question, you can use
type User = { name: string; age: number; [key: string]: any };
CodePudding user response:
- How to explain the difference in the behaviors above?
In the first line you are creating an anonymous object. So no type checking is applied. In the second line you are specifically telling typescript that your object is of type User, so compile-time check was applied.
- How do I declare a type that will cause the object to AT LEAST have all the necessary properties from the User type, and the rest of the properties can be completely different?
You can take help of Intersection typescript types. something like this
type User = { name: string, age: number };
type NewUser = User & {[key:string]:any}
const user1: NewUser = { name: 'Harry', age: 21, skills: 'backend', isAdmin: true }