Home > database >  How to use enum from other file as parameter type on function in Typescript
How to use enum from other file as parameter type on function in Typescript

Time:10-24

I am trying to put all of my enum on 1 file called Constants.ts and from it all the enum will be called, including as a parameter type on a function. But when I try to use it as parameter type on function in other class, it th

'Constants' only refers to a type, but is being used as a namespace here.ts(2702)

Here is my Constants.ts:

// Constants.ts
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

//TEST
enum GameState
{
     START_SCREEN = "start_screen",
}

@ccclass('Constants')
export class Constants extends Component {
  public static GameState = GameState;

}

and then I tried to use GameState on other file GameManager.ts

//GameManager.ts
import { _decorator, Component, Node, resources, Prefab, view, instantiate, find, director, Vec3, game, sys } from 'cc';
import { Constants } from './Constants';

const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {

static active_state;

public static set_State(state: Constants.GameState): void
{
    GameManager.active_state = state;
}

}

at this point, it threw me that error.

Anyone can enlighten me about this?

CodePudding user response:

You’re trying to use a (potentially) dynamic value as a static type. For example:

class Vault {
    static key = “a string”;
}

function run(secret: Vault.key) {…}

// vs using a literal(which is an actual type)

type VaultKey = “a string”;

function run(secret: VaultKey);

You should just export your enum from the constants module and then import it as a type directly from the module rather than as a property of an exported class.

Like

// constants.ts
export enum Color {…}

// main.ts
import { Color } from “constants.ts”:

function run(color: Color) {…}
  • Related