Can we reference the type of one variable (let's call it someVar
) in TypeScript when declaring the type of another variable (anotherVar
)?
For example, instead of creating a separate type declaration for { complex: 'type' }
, can we directly use it as the type for someVar
? And then, later in the code, is it possible to conditionally assign the value of someVar
to anotherVar
or leave it undefined without resorting to using any
?
const someVar?: { complex: 'type' } // = ...
// ...
// Desired behavior in pseudocode:
let anotherVar/*: (typeof someVar) */ = undefined
if (condition) {
anotherVar = someVar
}
Update: TypeScript does have a typeof
operator that can achieve this (the above pseudocode is valid TypeScript code), but there are limitations, especially when working with this
.
Here's a slightly different scenario:
class Test {
private someVar?: { complex: 'type' } // = ...
private someMethod() {
let anotherVar: typeof this.someVar = undefined // Error: Cannot find name 'this'.
if (condition) {
anotherVar = someVar
}
}
}
In the case above, how can we address the issue?