Reputation: 99970
Say I have this in a file:
export default {
foo: true
bar: 'zam',
baz: 4
}
this will generated a .d.ts file like:
declare const _default: {
foo: boolean;
bar: string;
baz: number;
}
export default _default;
my question is - is there a way to generate an interface from either of these structures? It would be nice to be able to avoid the need to generate an interface manually.
This might not be possible, and in that case, I am wondering - how do I declare an interface and have a const implement that interface? Sounds like a dumb question, but I don't actually know the best way to do that.
Upvotes: 1
Views: 1140
Reputation: 6456
You can use typeof
to get the type structure of a const object.
const Foo = {
foo: true,
bar: 'zam',
baz: 4,
}
// type FooType = { foo: boolean, bar: string, baz: number }
type FooType = typeof Foo;
const FooImpl: FooType = {
foo: true,
bar: 'zam',
} // will complain because I'm missing `baz`
Two notes of concern though:
class MyClass extends FooType
).const myInt = 3
has type myInt: 3
, the object const myObj = { myInt: 3 }
would have the type myObj: { myInt: number }
.Upvotes: 2