patterntypescriptCritical
Is there a way to "extract" the type of TypeScript interface property?
Viewed 0 times
typescriptpropertyextracttheinterfacewaytypethere
Problem
Let's suppose there's a typing file for library X which includes some interfaces.
In order to work with this library I need pass around an object that is of exactly the same type as
but then I get the burden of keeping it up to date with the one from library, moreover it can be very large and result in lot of code duplication.
Therefore, is there any way to "extract" the type of this specific property of the interface? Something similar to
Edit: after playing a bit in TS Playground I noticed that following code achieves exactly what I want to:
However it requires a redundant variable
interface I1 {
x: any;
}
interface I2 {
y: {
a: I1,
b: I1,
c: I1
}
z: any
}In order to work with this library I need pass around an object that is of exactly the same type as
I2.y. I can of course create identical interface in my source files:interface MyInterface {
a: I1,
b: I1,
c: I1
}
let myVar: MyInterface;but then I get the burden of keeping it up to date with the one from library, moreover it can be very large and result in lot of code duplication.
Therefore, is there any way to "extract" the type of this specific property of the interface? Something similar to
let myVar: typeof I2.y (which doesn't work and results in "Cannot find name I2" error).Edit: after playing a bit in TS Playground I noticed that following code achieves exactly what I want to:
declare var x: I2;
let y: typeof x.y;However it requires a redundant variable
x to be declared. I am looking for a way to achieve this without that declaration.Solution
It wasn't possible before but luckily it is now, since TypeScript version 2.1. It was released on the 7th of December 2016 and introduces indexed access types, also called lookup types.
The syntax looks like element access but is written in place of types. So in your case:
Now
Check it out in TypeScript Playground.
The syntax looks like element access but is written in place of types. So in your case:
interface I1 {
x: unknown;
}
interface I2 {
y: {
a: I1,
b: I1,
c: I1,
}
z: unknown,
}
const myVar: I2['y']; // indexed access typeNow
myVar has the type of I2.y.Check it out in TypeScript Playground.
Code Snippets
interface I1 {
x: unknown;
}
interface I2 {
y: {
a: I1,
b: I1,
c: I1,
}
z: unknown,
}
const myVar: I2['y']; // indexed access typeContext
Stack Overflow Q#36311284, score: 669
Revisions (0)
No revisions yet.