Reputation: 21698
I have been using typescript from 1 years and every time I need an object to pass, I need to do it in ugly way or manually.
In typescript there are interfaces for type definition and holds all the parameter we need. Is there a way we can create object out of it?
example:
export interface User {
name: string;
email: string;
}
I want below code to be automated which I cannot do it from interface rater I have create a class with constructor.
user {
name: ''/null/undefined,
email: ''/null/undefined
}
let user: User = new User() // this will show error
But I can create a new object out of below class.
export class User {
constructor() {
name: string;
email: string;
}
}
new User();
Which one is batter? creating a constructor class or interface?
Upvotes: 3
Views: 8467
Reputation: 147
I don't think there is a way.
Interface and class are two different thing and have different use cases. Interfaces are just structure and cannot have a instance, You you will see the compiled typescript which is generated JavaScript, you will not find interfaces anywhere.
So the interfaces are only at compile time and not run time.
But the classes are run time. So when you say new User(), it create instance of that class as it is there in the generated JavaScript.
you can also explore abstract class if it fits in your situation.
Upvotes: 2
Reputation: 3611
Yes, you can assign value to the interface directly and by the looks of it if you do not need to assign/instantiate all the properties defined in the interface then you can mark them as optional using ?
. In the following example email, is marked as optional and the subsequent assignment of user will be a valid statement.
interface User {
name: string;
email?: string;
}
let user: User = { name: '' };
Upvotes: 3