简体   繁体   中英

TypeScript 1.8 definition file Enum for 'magic string' properties

I have a js lib I need to use in a tsc 1.8 project. One of its option properties is a magic string which states it only supports a few values, ie 'default', 'option 1', 'option 2'. In my .d.ts I would like to use an Enum for this value but cant work out how to do it. for example...

loggerjs.js (external lib example)

var loggerjs = (function(){
    function log(severity) {
        var message;

        if (severity === "High") {
            message = "OMG!";
        }
        else if (severity === "Low") {
            message = "meh";
        }

        console.log(message)
    }
});

loggerjs.d.ts

declare module "loggerjs" {
    export enum Severity {
        "Low",
        "High"
    }

    export function log(severity: Severity);
}

require config

requirejs.config({
    baseUrl: '',
    paths: {
        app: ''
    },
    shim:{
        'loggerjs':{
            exports:'loggerjs'
        }
    }
});

requirejs(['app']);

app.ts

import * as loggerjs from "loggerjs";
loggerjs.log(loggerjs.Severity.Low);

app.js (compiled js)

define(["require", "exports", "loggerjs"], function (require, exports, loggerjs) {
    "use strict";
    loggerjs.log(loggerjs.Severity.Low);
});

The above results in

app.js:3 Uncaught TypeError: Cannot read property 'Low' of undefined

Enum isn't what you're after because that js uses strings.
You're getting that error because the actual implementation does not have that enum, you only declared that it does.

What you are looking for is called String Literal Types and it would look like this:

declare module "loggerjs" {
    export type Severity = "Low" | "High";

    export function log(severity: Severity);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM