Alexander Mills
Alexander Mills

Reputation: 99970

Generate TypeScript interface from const

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

Answers (1)

y2bd
y2bd

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:

  • As FooType is a type, and not an interface, you cannot use it in all the places that you would normally use interfaces (e.g. class MyClass extends FooType).
  • The types of the keys of const objects fall back to their general type. Essentially, while const myInt = 3 has type myInt: 3, the object const myObj = { myInt: 3 } would have the type myObj: { myInt: number }.

Upvotes: 2

Related Questions