Javascript Typescript 强类型键值对声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33141160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:41:44  来源:igfitidea点击:

Typescript strongly typed key value pair declaration

javascriptjsontypescript

提问by ZZZ

I would like to declare a TypeScript interface for such json structure:

我想为这样的 json 结构声明一个 TypeScript 接口:

{ 
404: function() { alert( "page not found" ); }, 
400 : function() {...} 
}

the key is number, and the value is function, do you know how to declare an interface in TypeScript for such data constraints?

key是number,value是function,你知道如何在TypeScript中为这样的数据约束声明一个接口吗?

回答by Fenton

Indexer

索引器

You canuse numbers as keys in JavaScript if you use []key access...

如果您使用按键访问,您可以在 JavaScript 中使用数字作为按键[]...

Let's start with your desired code...

让我们从您想要的代码开始...

var x = { 
    404: function() { alert( "page not found" ); }, 
    400 : function() { alert("...");} 
};

x.404();

The last statement above (the call to the 404function) will error with Missing ; before statement, so you have to use...

上面的最后一条语句(对404函数的调用)将出错Missing ; before statement,因此您必须使用...

x[404]();

While this will still get you type inference in TypeScript (var a = x[404];- awill be type () => void) - it won't give you good auto-completion.

虽然这仍然会让你在 TypeScript 中进行类型推断(var a = x[404];-a将是 type () => void) - 它不会给你很好的自动完成。

Interface for this:

接口:

interface HttpCodeAlerts {
   [index: number]: () => void;
}

With Auto-Completion

自动完成

Normally in JavaScript and TypeScript it is recommended that you use safer names. Simplistically, you need to start them with a letter:

通常在 JavaScript 和 TypeScript 中,建议您使用更安全的名称。简单地说,您需要以字母开头:

var x = { 
    E_404: function() { alert( "page not found" ); }, 
    E_400 : function() { alert("...");} 
};

x.E_404();

Interface for this:

接口:

interface HttpCodeAlerts {
    E_400: () => void;
    E_404: () => void;
}

Framework Style

框架风格

In most languages, the error is used more like this...

在大多数语言中,错误更像是这样使用的......

class HttpCode { 
    static OK = { responseCode: 200, reasonPhrase: 'Okay' };
    static NotFound = { responseCode: 404, reasonPhrase: 'Not Found' };
};

alert(HttpCode.NotFound.reasonPhrase);

回答by vitrilo

See TypeScript Objects as Dictionary types as in C#

TypeScript 对象视为 C# 中的字典类型

var map: { [code: number]: ()=>void; } = { };
//usage
map[404] = ()=> { alert("page not found"); }; 
map[400] = ()=> { alert("..."); };
map["some"] = "some"; //compile error

//all in once
var map: { [code: number]: ()=>void; } = {
   404: () => { alert( "page not found" ); }, 
   400: () => { alert( "..." )} 
};

回答by Ajay

This can probably be one of the answer :-

这可能是答案之一:-

export interface clientSideFunction{
    [code: number]: ()=>void;
}

use this interface by importing it using:-

通过使用以下方式导入它来使用此接口:-

import {clientSideFunction} from 'filePath';

回答by ahz

It is not valid JSON structure thus not valid JavaScript (neither TypeScript). Object keys should be strings. According to this answernumbers are always converted to strings.

它不是有效的 JSON 结构,因此不是有效的 JavaScript(也不是 TypeScript)。对象键应该是字符串。根据此答案,数字始终转换为字符串。

Therefore I suggest to use explicit strings as keys in your JSON. Then you can model it in TypeScript like this:

因此,我建议在 JSON 中使用显式字符串作为键。然后你可以像这样在 TypeScript 中对其进行建模:

interface ICodes {
    "404": () => void;
    [code: string]: () => void; // defines any string key to be function
}

var codes: ICodes = {
    "404": function () { alert("page not found"); },
    "400": function () {}
};

// call the function for code 404
codes["404"]();