I'm learning Generics in Typescript and have one problem with implementation generic interface.
My interface
export interface ToTable<T> {
value: T
toColumns(): Column
fromColumn<T>():T
}
I want to class which implements this interface have this field and methods which works with Column class.
export class Column {
field: string = ''
value: string = ''
}
and when I try to implement interface in User class
export class UserService implements ToTable<User> {
value: User
constructor() {
this.value = new User()
}
fromColumn<User>(columns: Column[]): User {
return this.value
}
toColumns(): Column {
let col = new Column()
col.field = 'name'
col.value = 'testVal'
return col
}
}
in method "fromColumn" that should return User class object, I got error:
Type 'import("c:/Projects/Train-Projects/Test-directives/src/app/servisec/user").User' is not assignable to type 'User'.
'User' could be instantiated with an arbitrary type which could be unrelated to 'import("c:/Projects/Train-Projects/Test-directives/src/app/servisec/user").User'.ts(2322)
User type in fromColumn method is not same with User class?
Since you are defining your generic parameters in the interface definition, you don't need to declare it in your
fromColumnfunction as well. You can just reuse it.As for your error, it seams to be fixed when you remove the generic parmeter from your function declaration. It might be caused by the fact that you do not import the same
Userobject in both files.However, there is still an issue with your code. Your interface is not declaring any parameter in the
fromColumnfunction, which will cause an error in thefromColumnfunction defined in yourUserService. You might want to add thecolumnsparameter to yourfromColumninterface :Here is the playground I've use to test your code