Typescript newbie here. Let's say I have a type coming from a library that looks like this:
type FooType {
name: string;
// Has much more attributes in real life
}
I now want to define a class called Foo
like this:
import { FooType } from 'my-library';
class Foo {
constructor(data: FooType) {
Object.assign(this, data);
}
}
With this code, I'm able to define a foo instance, yet I have an issue with autocomplete:
const foo = new Foo({ name: 'foo name' });
// Typing in foo.name does not bring any type information about the "name" attribute
Is there a way I can make a class automatically "inherit" all attributes from a type without having to type them manually?
Edit after being marked as duplicate:
What I want to achieve is to avoid manually typing attributes that are already existing on a type.
Thanks to @Phil I've been provided an answer that mentions this as an ongoing issue within Typescript: https://github.com/microsoft/TypeScript/issues/26792
What I will do for now is the following:
class Foo {
constructor(public _data: FooType)
Object.assign(this, _data);
}
get() {
return this._data;
}
}
const foo = new Foo({ name: 'Bar' });
foo.get().name; // After typing "foo.get()" the autocomplete works properly.