Is there any way to declare a variable with the type of another variable? For instance, I declare a class member with some type, and then later I want to declare another variable in a function of the same type. But I don't want to modify the original declaration, and don't want to duplicate it. It seems like you should be able to do something like:
class Foo {
bar: {[key: string]: string[]};
func() {
const x: TypeOf<Foo.bar> = {};
....
}
}
I've heard of something like this specifically for return types of functions, but I can't find it anymore...
TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.
The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.
*Note that sometimes a variable can work as more than one type!
Yes, it is okay to reuse the same symbol for a variable in different "scopes". A quantifier binds the variable that it introduces within the subexpression headed by that quantifier.
You can use typeof
but in class you should get to property:
class Foo {
bar: {[key: string]: string[]};
func() {
const x: typeof Foo.prototype.bar = {};
// here x has type `{[key: string]: string[]}`
}
}
And another example outside of class:
class A {
b: string = ''
}
type test = typeof A.prototype.b // type is `string`
PlayGround
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With