最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create interface from typeof? - Stack Overflow

programmeradmin0浏览0评论

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
}

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
}
Share Improve this question edited Jul 21, 2018 at 7:04 jonrsharpe 122k30 gold badges267 silver badges474 bronze badges asked Jul 21, 2018 at 6:54 Ray ZhangRay Zhang 1,5615 gold badges19 silver badges39 bronze badges 4
  • I hate to ask the annoying question, because you have a reason, but I gotta ask, in a prototypal language that Typescript is a superset of (Javascript), why are you trying to do this? Just define const o: i – Brian Ogden Commented Jul 21, 2018 at 6:59
  • 1 TypeScript doesn't exist at runtime, so "dynamically" doesn't really make sense. What's the underlying requirement here? – jonrsharpe Commented Jul 21, 2018 at 7:04
  • 2 Just use type instead of interface: type i = typeof o; – artem Commented Jul 21, 2018 at 7:07
  • 1 No easy way to do this I suspect, especially concerning objects with nested objects. – jonny Commented Jul 21, 2018 at 8:27
Add a ment  | 

1 Answer 1

Reset to default 11

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 = ''
}
发布评论

评论列表(0)

  1. 暂无评论