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 = ''
}