Ray Zhang
Ray Zhang

Reputation: 1561

How to create interface from typeof?

How do I dynamically go "backwards" from object to interface?

const o = {
  a: 1,
  b: "hi"
}

interface i = typeof o; // how to write this?

The result should be equivalent to:

interface i {
  a: number,
  b: string
}

Upvotes: 5

Views: 3760

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249716

You can't directly create an interface, but you can create a type alias, which you can in most casses be used the same as an interface (ie. You can extend a new interface from it or implement it in a class

const o = {
a: 1,
b: "hi"
}

type i = typeof o; 
interface ii extends i { }
class ci implements i {
    a = 1;
    b = ''
}

Upvotes: 11

Related Questions