Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: declare variable with same type as another

Tags:

typescript

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...

like image 733
zacaj Avatar asked Oct 11 '19 13:10

zacaj


People also ask

How do you declare a variable with two types TypeScript?

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.

How do you assign a type to a variable in TypeScript?

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.

Can a variable be two types?

*Note that sometimes a variable can work as more than one type!

Can you use the same variable twice?

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.


1 Answers

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

like image 110
Ivan Avatar answered Oct 23 '22 03:10

Ivan