admin管理员组文章数量:1305997
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 ofinterface
: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
1 Answer
Reset to default 11You 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 = ''
}
本文标签: javascriptHow to create interface from typeofStack Overflow
版权声明:本文标题:javascript - How to create interface from typeof? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741814597a2398998.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论