TypeScript:如何将参数类型注释为“对象的任何值”?

Gur*_*ofu 0 types typescript

我应该如何将参数类型注释为“对象的任何值”?

class ExampleClass {

    private static readonly MODES = {
        DEVELOPMENT: 0,
        PRODUCTION: 1,
        TEST: 2
    }

    //  Any Value of ExampleClass.MODES
    constructor(mode: MODE[?]) {

    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,价值012都好像在使用无意义的enum,但据我所知,我们不能用enum作为类字段。因此,让我们考虑some value of object这个问题的情况。

Mat*_*hen 5

Tomas非常接近,但让我们继续给出完整的答案。要获取的值类型typeof MODES,只需按其所有键的类型为其编制索引。

type ValueOf<T> = T[keyof T];

// Prevent widening of the types of the constants to `number`.
function asLiterals<T extends number, U extends { [n: string]: T }>(arg: U) {
    return arg;
}

class ExampleClass {

    private static readonly MODES = asLiterals({
        DEVELOPMENT: 0,
        PRODUCTION: 1,
        TEST: 2
    });

    //  Any Value of ExampleClass.MODES
    constructor(mode: ValueOf<typeof ExampleClass.MODES>) {

    }
}
Run Code Online (Sandbox Code Playgroud)