这种类型声明在Typescript中意味着什么?

时间:2016-06-18 15:06:41

标签: typescript

我是打字稿的新手,而且我正在阅读其他人的代码并且无法使用此声明:

    private somevar: { [s: string]: string };

这是什么类型的?方括号表示一个数组,但是我确切地想知道它的形状是什么。

2 个答案:

答案 0 :(得分:10)

它是一种可转位类型。查看此变量定义的类型表达式:

<section class="content">
    <div class="box">
        <div class="box-body">

            <%= simple_form_for :ride, url: order_path do |f| %>

            <p>
                <%= f.label :client %><br>
                <%= f.text_field :client %>
            </p>

            <p>
                <%= f.submit 'Adicionar', :class => 'btn btn-primary' %>
            </p>

            <% end %>

        </div>
    </div>
</section>
  • let myIndexVar: { [key: string]: number; }; 表示它是一个对象。
  • : { ... }是对象的索引签名。

在索引签名中:

  • [key: string]: number;定义了密钥的名称 - [key: string] - 以及密钥的类型 - key
  • string是值的类型 - : number;

这些类型的用法如下:

number

请注意,您可以为密钥指定任何您喜欢的名称。给它一个描述性名称有助于说出密钥是什么,尽管变量名也应该这样做:

Intellisense example

答案 1 :(得分:1)

通过David Sherret

进一步解释答案

来自Typscript docs

  

可索引类型与我们如何使用接口来描述函数类型类似,我们也可以描述可以“索引到”的类型   像[10]或ageMap [&#34; daniel&#34;]。可索引类型具有索引   签名,描述我们可以用来索引的类型   对象,以及索引时的相应返回类型。让我们   举个例子:

interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];
     

上面,我们有一个具有索引签名的StringArray接口。   此索引签名表明当StringArray使用a索引时   数字,它将返回一个字符串。

     

支持的索引签名有两种类型:字符串和数字。   可以支持两种类型的索引器,但类型   从数字索引器返回的必须是返回类型的子类型   来自字符串索引器。这是因为当用数字索引时,   在索引之前,JavaScript实际上会将其转换为字符串   一个东西。这意味着使用100(数字)的索引是相同的   用&#34; 100&#34;索引的东西(一个字符串),所以这两个需要   是一致的。

class Animal {
    name: string;
}
class Dog extends Animal {
    breed: string;
}

// Error: indexing with a 'string' will sometimes get you a Dog!
interface NotOkay {
    [x: number]: Animal;
    [x: string]: Dog;
}
     

虽然字符串索引签名是一种强大的描述方式   “字典”模式,他们还强制所有属性匹配   他们的回报类型。这是因为字符串索引声明了这一点   obj.property也可以作为obj [&#34; property&#34;]。在下面的   例如,name的类型与字符串索引的类型不匹配   type-checker会出错:

interface NumberDictionary {
    [index: string]: number;
    length: number;    // ok, length is a number
    name: string;      // error, the type of 'name' is not a subtype of the indexer
}
相关问题