theapache64
theapache64

Reputation: 11734

How to access static class member from an interface

First of all, I am new in TypeScript and this question might be simple for you :/.

I've a car class that has a static member variable, a number, named NUMBER_OF_WHEELS. I've an interface also named CarProps that has wheels property which can be either a number or NUMBER_OF_WHEELS.

interface CarProps {
    wheels: number[] | Car.NUMBER_OF_WHEELS
}

class Car {
    public static readonly NUMBER_OF_WHEELS = 4;
}

but when I try to access NUMBER_OF_WHEELS from CarProps. I am getting

TS2702: 'Car' only refers to a type, but is being used as a namespace here.

enter image description here

Upvotes: 0

Views: 182

Answers (1)

Ziggy
Ziggy

Reputation: 22365

Welcome to Typescript!

Typescript provides annotations on top of javascript to describe the types of the data in a program. It does its work during the compile step, before any code runs. The reason you can't "access" a static property of a class and use it as a type is that static properties (even very readonly ones) are still part of the runtime value of the class.

What you need is a type! Try this:

type NUMBER_OF_WHEELS = 4 // this is a type, the type is '4'

interface CarProps {
    wheels: number[] | NUMBER_OF_WHEELS
}

class Car {
    // the type of this variable is '4' so it can ONLY be assigned the value 4
    public static readonly NUMBER_OF_WHEELS: NUMBER_OF_WHEELS = 4;
}

This is the answer: typescript happens before any variables are assigned any values. So typescript can't inspect values of variables. On the other hand, because typescript happens before any variables are assigned any values, you can use typescript to narrow the possible values that can be assigned to variables.

Types come first.


Finally: when posting a question on stack overflow, you will get a more helpful answer if you post real code. This question, as posed, seems like it is just a misconception about when compile time is. If you post the real code you are working on, then someone might be able to suggest a different approach to the problem and help lead you to some more satisfying answer.

Upvotes: 3

Related Questions