17

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

2
  • 7
    You can write const x: Foo["bar"] = ... to determine the type. Commented Oct 11, 2019 at 13:54
  • Similar questions provide further context. Commented Sep 1, 2022 at 15:26

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

consider typeof this['b']
1

Another way:

class Foo {
    bar: {[key: string]: string[]};

    func() {
        const x: Foo['bar'];
    }
}

It's called indexed access

More: https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html#handbook-content

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.