mirror of
https://github.com/gnu4cn/ts-learnings.git
synced 2025-01-28 05:10:12 +08:00
699 lines
64 KiB
HTML
699 lines
64 KiB
HTML
|
|
<!DOCTYPE HTML>
|
|
<html lang="" >
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
|
<title>接口 · GitBook</title>
|
|
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
|
<meta name="description" content="">
|
|
<meta name="generator" content="GitBook 3.2.3">
|
|
|
|
|
|
|
|
|
|
<link rel="stylesheet" href="gitbook/style.css">
|
|
|
|
|
|
|
|
|
|
<link rel="stylesheet" href="gitbook/gitbook-plugin-highlight/website.css">
|
|
|
|
|
|
|
|
<link rel="stylesheet" href="gitbook/gitbook-plugin-search/search.css">
|
|
|
|
|
|
|
|
<link rel="stylesheet" href="gitbook/gitbook-plugin-fontsettings/website.css">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<meta name="HandheldFriendly" content="true"/>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
|
<meta name="apple-mobile-web-app-capable" content="yes">
|
|
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
|
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
|
|
<link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">
|
|
|
|
|
|
<link rel="next" href="05_functions.html" />
|
|
|
|
|
|
<link rel="prev" href="03_classes.html" />
|
|
|
|
|
|
</head>
|
|
<body>
|
|
|
|
<div class="book">
|
|
<div class="book-summary">
|
|
|
|
|
|
<div id="book-search-input" role="search">
|
|
<input type="text" placeholder="Type to search" />
|
|
</div>
|
|
|
|
|
|
<nav role="navigation">
|
|
|
|
|
|
|
|
<ul class="summary">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<li class="chapter " data-level="1.1" data-path="./">
|
|
|
|
<a href="./">
|
|
|
|
|
|
Introduction
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
<li class="chapter " data-level="1.2" data-path="01_basic_data_types.html">
|
|
|
|
<a href="01_basic_data_types.html">
|
|
|
|
|
|
基本数据类型
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
<li class="chapter " data-level="1.3" data-path="02_variables_declaration.html">
|
|
|
|
<a href="02_variables_declaration.html">
|
|
|
|
|
|
变量声明
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
<li class="chapter " data-level="1.4" data-path="03_classes.html">
|
|
|
|
<a href="03_classes.html">
|
|
|
|
|
|
类
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
<li class="chapter active" data-level="1.5" data-path="04_interfaces.html">
|
|
|
|
<a href="04_interfaces.html">
|
|
|
|
|
|
接口
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
<li class="chapter " data-level="1.6" data-path="05_functions.html">
|
|
|
|
<a href="05_functions.html">
|
|
|
|
|
|
函数
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
<li class="chapter " data-level="1.7" data-path="06_generics.html">
|
|
|
|
<a href="06_generics.html">
|
|
|
|
|
|
泛型
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
<li class="chapter " data-level="1.8" data-path="07_enums.html">
|
|
|
|
<a href="07_enums.html">
|
|
|
|
|
|
枚举
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
<li class="chapter " data-level="1.9" data-path="08_type_inference.html">
|
|
|
|
<a href="08_type_inference.html">
|
|
|
|
|
|
类型推导
|
|
|
|
</a>
|
|
|
|
|
|
|
|
</li>
|
|
|
|
|
|
|
|
|
|
<li class="divider"></li>
|
|
|
|
<li>
|
|
<a href="https://www.gitbook.com" target="blank" class="gitbook-link">
|
|
Published with GitBook
|
|
</a>
|
|
</li>
|
|
</ul>
|
|
|
|
|
|
</nav>
|
|
|
|
|
|
</div>
|
|
|
|
<div class="book-body">
|
|
|
|
<div class="body-inner">
|
|
|
|
|
|
|
|
<div class="book-header" role="navigation">
|
|
|
|
|
|
<!-- Title -->
|
|
<h1>
|
|
<i class="fa fa-circle-o-notch fa-spin"></i>
|
|
<a href="." >接口</a>
|
|
</h1>
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div class="page-wrapper" tabindex="-1" role="main">
|
|
<div class="page-inner">
|
|
|
|
<div id="book-search-results">
|
|
<div class="search-noresults">
|
|
|
|
<section class="normal markdown-section">
|
|
|
|
<h1 id="接口(interfaces)">接口(Interfaces)</h1>
|
|
<h2 id="简介">简介</h2>
|
|
<p>TypeScript语言的核心原则之一,就是类型检查着重于值所具有的 <em>形(shape)</em>(One of TypeScript's core principles is that type-checking focuses on the <em>shape</em> that values have)。这有时候被称为“<a href="https://zh.wikipedia.org/wiki/%E9%B8%AD%E5%AD%90%E7%B1%BB%E5%9E%8B" target="_blank">鸭子类型(duck typing)</a>” 或 “<a href="https://openhome.cc/Gossip/Scala/StructuralTyping.html" target="_blank">结构化子类型(structural subtyping)</a>”。在TypeScript中,接口充当了这些类型名义上的角色,且是一种定义代码内的合约(约定),以及与项目外部代码的合约约定的强大方式(In TypeScript, interfaces fill the role of naming these types, and are a powerfull way of defining contracts within your code as well as contracts with code outside of your project)。</p>
|
|
<h2 id="接口初步(our-first-interface)">接口初步(Our First Interface)</h2>
|
|
<p>理解接口的最容易方式,就是从一个简单的示例开始:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printLable</span> (<span class="hljs-params">labelledObj: { label: <span class="hljs-built_in">string</span> }</span>) </span>{
|
|
<span class="hljs-built_in">console</span>.log(labelledObj.label);
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> myObj = {size: <span class="hljs-number">10</span>, label: <span class="hljs-string">"Size 10 Object"</span>};
|
|
|
|
printLable(myObj);
|
|
</code></pre>
|
|
<p>类型检查器对<code>printLable</code>的调用进行检查。函数<code>printLable</code>有着一个单独参数,该参数要求所传入的对象要有一个名为<code>label</code>、类型为字符串的属性。请注意这里的<code>myObj</code>实际上有着更多的属性,但编译器对传入的参数只检查其 <em>至少</em> 有着列出的属性,且要匹配要求的类型。当然也存在TypeScript编译器不那么宽容的情形,这一点在后面会讲到。</p>
|
|
<p>可以再次编写此示例,这次使用接口来描述需要具备<code>label</code>属性这一要求:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> LabelledValue {
|
|
label: <span class="hljs-built_in">string</span>;
|
|
}
|
|
|
|
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printLable</span> (<span class="hljs-params"> labelledObj: LabelledValue </span>) </span>{
|
|
<span class="hljs-built_in">console</span>.log(labelledObj.label);
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> myObj = { size: <span class="hljs-number">10</span>, label: <span class="hljs-string">"Size 10 Object"</span> };
|
|
printLable (myObj);
|
|
</code></pre>
|
|
<p>这里的<code>LabelledValue</code>接口,是一个立即可用于描述前一示例中的要求的名称。它仍然表示有着一个名为<code>label</code>、类型为字符串的属性。请注意这里并没有像在其它语言中一样,必须显式地说传递给<code>printLable</code>的对象应用该接口。这里只是那个 <em>形(shape)</em> 才是关键的。如果传递给该函数的对象满足了列出的要求,那么就是允许的。</p>
|
|
<p>这里需要指出的是,类型检查器不要求这些属性以何种顺序进入,只要有接口所要求的属性及类型即可。</p>
|
|
<h2 id="可选属性(optional-properties)">可选属性(Optional Properties)</h2>
|
|
<p>接口可以包含并不需要的属性。在特定条件下某些属性存在,或根本不存在(Not all properties of an interface may be required. Some exist under certain conditions or may not be there at all)。在建立像是那种将某个仅有少数属性的对象,传递给某个函数的“选项包(option bags)”的模式时,这些可选属性用得比较普遍。</p>
|
|
<p>下面是此种模式的一个示例:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> SquareConfig {
|
|
color?: <span class="hljs-built_in">string</span>;
|
|
width?: <span class="hljs-built_in">number</span>;
|
|
}
|
|
|
|
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createSquare</span> (<span class="hljs-params"> config: SquareConfig </span>): </span>{color: <span class="hljs-built_in">string</span>; area: <span class="hljs-built_in">number</span>} {
|
|
<span class="hljs-keyword">let</span> newSquare = {color: <span class="hljs-string">"white"</span>, area: <span class="hljs-number">100</span>};
|
|
|
|
<span class="hljs-keyword">if</span> (config.color) {
|
|
newSquare.area = config.with * config.width;
|
|
}
|
|
|
|
<span class="hljs-keyword">return</span> newSquare;
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> mySquare = createSquare({color: <span class="hljs-string">"black"</span>});
|
|
</code></pre>
|
|
<p>带有可选属性的接口,其写法与其它接口相似,只需在各个可选属性的声明中,在属性名字的末尾,以<code>?</code>加以表示即可。</p>
|
|
<p>使用可选属性的优势在于,在对可能存在的属性进行描述的同时,仍然可以阻止那些不是该接口组成部分的属性的使用。比如在将<code>createSquare</code>中的<code>color</code>属性错误拼写的情况下,就会收到提醒的错误消息:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> SquareConfig {
|
|
color?: <span class="hljs-built_in">string</span>;
|
|
width?: <span class="hljs-built_in">number</span>;
|
|
}
|
|
|
|
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createSquare</span> (<span class="hljs-params"> config: SquareConfig </span>): </span>{ color: <span class="hljs-built_in">string</span>; area: <span class="hljs-built_in">number</span> } {
|
|
<span class="hljs-keyword">let</span> newSquare = { color: <span class="hljs-string">"white"</span>, area: <span class="hljs-number">100</span> };
|
|
<span class="hljs-comment">//Property 'clor' does not exist on type 'SquareConfig'. Did you mean 'color'? (2551) </span>
|
|
<span class="hljs-keyword">if</span> (config.color) {
|
|
newSquare.color = config.clor;
|
|
}
|
|
|
|
<span class="hljs-keyword">if</span> ( config.width ) {
|
|
newSquare.area = config.width * config.width;
|
|
}
|
|
|
|
<span class="hljs-keyword">return</span> newSquare;
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> mySquare = createSquare({color: <span class="hljs-string">"black"</span>});
|
|
</code></pre>
|
|
<h2 id="只读属性(readonly-properties)">只读属性(Readonly properties)</h2>
|
|
<p>一些属性只应在对象刚被创建时是可修改的。那么可通过将<code>readonly</code>关键字放在该属性名称前,对这些属性加以指定。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Point {
|
|
readonly x: <span class="hljs-built_in">number</span>;
|
|
readonly y: <span class="hljs-built_in">number</span>;
|
|
}
|
|
</code></pre>
|
|
<p>就可以通过指派一个对象文字(an object literal),构建出一个<code>Point</code>出来。在赋值过后,<code>x</code>与<code>y</code>就再也不能修改了。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> p1: Point = { x: <span class="hljs-number">10</span>, y: <span class="hljs-number">20</span> };
|
|
p1.x = <span class="hljs-number">5</span>; <span class="hljs-comment">//Cannot assign to 'x' because it is a constant or a read-only property. (2540)</span>
|
|
</code></pre>
|
|
<p>TypeScript 有着一个<code>ReadonlyArray<T></code>类型,该类型与<code>Array<T></code>一致,只是移除了所有变异方法(with all mutating methods removed),因此向下面这样就可以确保在某个数组创建出后,不会被修改:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> a: <span class="hljs-built_in">number</span>[] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
|
|
<span class="hljs-keyword">let</span> ro: ReadonlyArray<<span class="hljs-built_in">number</span>> = a;
|
|
ro[<span class="hljs-number">0</span>] = <span class="hljs-number">12</span>; <span class="hljs-comment">//Index signature in type 'ReadonlyArray<number>' only permits reading. (2542)</span>
|
|
ro.push(<span class="hljs-number">5</span>); <span class="hljs-comment">//Property 'push' does not exist on type 'ReadonlyArray<number>'. (2339) </span>
|
|
ro.length = <span class="hljs-number">100</span>;<span class="hljs-comment">//Cannot assign to 'length' because it is a constant or a read-only property. (2540)</span>
|
|
a = ro;<span class="hljs-comment">//Type 'ReadonlyArray<number>' is not assignable to type 'number[]'</span>
|
|
</code></pre>
|
|
<p>上面这段代码中最后一行可以看出,将整个<code>ReadonlyArray</code>往回赋值给正常数组,也是非法的。但仍然可以使用一个类型断言(a type assertion),以消除此错误:</p>
|
|
<pre><code class="lang-typescript">a = ro as <span class="hljs-built_in">number</span>[];
|
|
</code></pre>
|
|
<h3 id="readonly-与-const的区别"><code>readonly</code> 与 <code>const</code>的区别</h3>
|
|
<p>对于要使用<code>readonly</code>或<code>const</code>,最简单的办法就是区分是要在变量上,还是属性上使用。对于变量,当然就用<code>const</code>,属性则用<code>readonly</code>。</p>
|
|
<h2 id="关于多余属性检查(excess-property-checks)">关于多余属性检查(Excess Property Checks)</h2>
|
|
<p>在采用了接口的第一个示例中,TypeScript令到可将<code>{size: number; label: string;}</code>传递给某些仅期望一个<code>{label: string;}</code>的地方。后面还介绍了关于可选属性,以及可选属性在名为“选项包(option bags)”的地方如何发挥作用。</p>
|
|
<p>但是,如像在JavaScript中那样,将这两个特性单纯地结合在一起,就足以杀死你自己,下面就用最后一个示例使用<code>createSquare</code>来说明一下:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> SquareConfig {
|
|
color?: <span class="hljs-built_in">string</span>;
|
|
width?: <span class="hljs-built_in">number</span>;
|
|
}
|
|
|
|
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createSquare</span> (<span class="hljs-params"> config: SquareConfig </span>): </span>{ color: <span class="hljs-built_in">string</span>; area: <span class="hljs-built_in">number</span> } {
|
|
<span class="hljs-comment">// ...</span>
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> mySquare = createSquare ({ colour: <span class="hljs-string">"red"</span>, width: <span class="hljs-number">100</span> });
|
|
</code></pre>
|
|
<p>注意这里给予<code>createSquare</code>的参数被写成了<code>colour</code>,而不是<code>color</code>。在普通的JavaScript中,这类错误将不会报错。</p>
|
|
<p>对于这个诚实,你可能会说没有错误拼写,因为<code>width</code>属性是兼容的,没有<code>color</code>属性出现,同时这里额外的<code>colour</code>属性是不重要的。</p>
|
|
<p>不过,TypeScript会认为在这段代码中存在问题。对象字面值会受到特别对待,同时在将对象字面值赋予给其它变量,或者将它们作为参数加以传递时,而收到 <em>多余属性检查</em>。如某个对象字面值有着任何目标对象不具有的属性时,就会报出错误。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-comment">// Argument of type '{ colour: string; width: number; }' is not assignable to parameter of type 'SquareConfig'.</span>
|
|
<span class="hljs-comment">// Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'? (2345)</span>
|
|
<span class="hljs-keyword">let</span> mySquare = createSquare({colour: <span class="hljs-string">"red"</span>, width: <span class="hljs-number">100</span>});
|
|
</code></pre>
|
|
<p>绕过此类检查实际上相当简单。最容易的做法就是使用一个类型断言(a type assertion):</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> mySquare = createSquare({width: <span class="hljs-number">100</span>, opacity: <span class="hljs-number">0.5</span>} as SquareConfig);
|
|
</code></pre>
|
|
<p>不过,在确定对象可能有某些在特别情况下会用到额外属性时,一种更好的方式就是为其添加一个字符串的索引签名(a string index signature)。比如在这里的<code>SquareConfig</code>们就可以有着上面<code>color</code>与<code>width</code>属性,但也可以具有任意数量的其它属性,那么就可以将其定义成下面这样:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> SquareConfig {
|
|
color?: <span class="hljs-built_in">string</span>;
|
|
width?: <span class="hljs-built_in">number</span>;
|
|
[propName: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">any</span>;
|
|
}
|
|
</code></pre>
|
|
<p>索引签名这个概念在后面会涉及,这里说的是<code>SquareConfig</code>可以有着任意数量的属性,而只要这些属性不是<code>color</code>或<code>width</code>就可以,它们的类型并不重要。</p>
|
|
<p>绕过这些检查的一种终极方式,可能有点意外,就是将该对象赋值给另一变量:因为<code>squareConfig</code>不会受多余属性检查,因此编译器也就不会给出错误。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> squareConfig = { colour: <span class="hljs-string">"red"</span>, width: <span class="hljs-number">100</span> };
|
|
<span class="hljs-keyword">let</span> mySquare = createSquare(squareConfig);
|
|
</code></pre>
|
|
<p>请记住对于像是上面的简单代码,一般不必尝试“绕过”这些检查。而对于更为复杂的、有着方法并存有状态的对象字面值(complex object literals that have methods and hold state),可能就要牢记这些技巧了,但大多数的多余属性错误,都是真实存在的bugs。那就意味着在使用诸如选项包(option bags)这类的特性,而出现多余属性检查类问题时,就应该对类型定义加以审视。在此实例中,如果允许将某个有着<code>color</code>或<code>colour</code>属性的对象传递给<code>createSquare</code>方法,那么就要修改<code>SquareConfig</code>的定义,来反应出这一点。</p>
|
|
<h2 id="函数的类型(function-types)">函数的类型(Function Types)</h2>
|
|
<p>对于描述JavaScript的对象所能接受的范围宽广的形,接口都是可行的(Interfaces are capable of describing the wide range of shapes that JavaScript objects can take)。除了用于描述带有属性的对象,接口还可以描述函数类型。</p>
|
|
<p>要用接口来描述函数,就要给予该接口一个调用签名(a call signature)。这就像是一个仅有着参数清单与返回值类型的函数声明。参数清单中的各参数,都要求名称与类型。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> SearchFunc {
|
|
(source: <span class="hljs-built_in">string</span>, subString: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">boolean</span>;
|
|
}
|
|
</code></pre>
|
|
<p>一旦定义好,就可以像使用其它接口一样,对此函数类型接口(this function type interface)进行使用了。这里展示了创建一个某种函数类型的变量,并把同一类型的函数值赋予给它的过程(create <em>a variable of a function type</em> and assign it <em>a function value</em> of the same type)。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> mySearch: SearchFunc;
|
|
mySearch = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">source: <span class="hljs-built_in">string</span>; subString: <span class="hljs-built_in">string</span></span>) </span>{
|
|
<span class="hljs-keyword">let</span> result = source.search(subString);
|
|
<span class="hljs-keyword">return</span> result > <span class="hljs-number">-1</span>;
|
|
}
|
|
</code></pre>
|
|
<p>参数名称无需匹配,就可以对函数类型进行正确的类型检查。比如这里可以像下面这样编写上面的示例:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> mySearch: SearchFunc;
|
|
mySearch = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">src: <span class="hljs-built_in">string</span>, sub: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">boolean</span> </span>{
|
|
<span class="hljs-keyword">let</span> result = src.search(sub);
|
|
<span class="hljs-keyword">return</span> result > <span class="hljs-number">-1</span>;
|
|
}
|
|
</code></pre>
|
|
<p>函数参数会逐一检查,以每个相应参数位置的类型,与对应的类型进行检查的方式进行(Function parameters are checked one at a time, with the type in each corresponding parameter position checked against each other)。如完全不打算指定类型,那么TypeScript的上下文类型系统就可以推断出参数类型,因为该函数值是直接赋予给<code>SearchFunc</code>类型的变量的。同时,这里函数表达式的返回值类型,是由其返回值(也就是<code>false</code>或<code>true</code>)隐式给出的。加入让该函数返回数字或字符串,那么类型检查器(the type-checker)就会发出返回值类型与<code>SearchFunc</code>接口中描述的返回值类型不符的警告。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> mySearch: SearchFunc;
|
|
mySearch = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">src, sub</span>) </span>{
|
|
<span class="hljs-keyword">let</span> result = src.search(sub);
|
|
<span class="hljs-keyword">return</span> result > <span class="hljs-number">-1</span>;
|
|
}
|
|
</code></pre>
|
|
<h2 id="可索引的类型(indexable-types)">可索引的类型(Indexable Types)</h2>
|
|
<p>与使用接口来描述函数类型类似,还可以使用接口类描述那些可以索引的类型(types that we can "index into"),比如<code>a[10]</code>,抑或<code>ageMap["daniel"]</code>这样的。可索引类型有着一个描述用于在该对象内部进行索引的类型的 <em>索引签名(index signature)</em>,以及在索引时返回值的类型。来看看这个示例:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> StringArray {
|
|
[index: <span class="hljs-built_in">number</span>]: <span class="hljs-built_in">string</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> myArray: StringArray;
|
|
myArray = [<span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Fred"</span>];
|
|
|
|
<span class="hljs-keyword">let</span> myStr: <span class="hljs-built_in">string</span> = myArray[<span class="hljs-number">0</span>];
|
|
</code></pre>
|
|
<p>在上面的代码中,有着一个带有索引签名的<code>StringArray</code>接口。此索引签名指出在某个<code>StringArray</code>以某个<code>number</code>加以索引时,它将返回一个<code>string</code>。</p>
|
|
<p>TypeScript支持的索引签名有两种类型:字符串及数字。同时支持这两种类型的索引器是可能的,但从某个数字的索引器所返回的类型,则必须是从字符串索引器所返回类型的子类型(It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer)。这是因为在以某个<code>number</code>进行索引时,JavaScript实际上会在对某个对象进行索引前,将其转换成<code>string</code>。也就是说,在使用<code>100</code>(<code>number</code>)来进行索引时,实际上与使用<code>"100"</code>(<code>string</code>)效果是一样的,因此二者就需要一致(That means that indexing with <code>100</code> (a <code>number</code>) is the same thing as indexing with <code>"100"</code> (a <code>stirng</code>), so the two need to be consistent)。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Animal {
|
|
name: <span class="hljs-built_in">string</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> Dog extends Animal {
|
|
breed: <span class="hljs-built_in">string</span>;
|
|
}
|
|
|
|
<span class="hljs-comment">// Numeric index type 'Animal' is not assignable to string index type 'Dog'. (2413)</span>
|
|
<span class="hljs-keyword">interface</span> NotOkay {
|
|
[x: <span class="hljs-built_in">number</span>]: Animal;
|
|
[x: <span class="hljs-built_in">string</span>]: Dog;
|
|
}
|
|
</code></pre>
|
|
<p>尽管字符串的索引签名是描述“字典”模式的一种强大方式,但它们同时强制了与它们的返回值类型匹配的属性值(While string index signatures are a powerful way to describe the "dictionary" pattern, they also enforce that all properties match their return type)。这是因为字符串的索引申明了<code>obj.property</code>同时与<code>obj["property"]</code>可用。在下面的示例中,<code>name</code>的类型与该字符串索引器的类型并不匹配,那么类型检查器就会给出一个错误:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-comment">//Property 'name' of type 'string' is not assignable to string index type 'number'. (2411)</span>
|
|
<span class="hljs-keyword">interface</span> NumberDictionary {
|
|
[index: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">number</span>;
|
|
length: <span class="hljs-built_in">number</span>;
|
|
name: <span class="hljs-built_in">string</span>;
|
|
}
|
|
</code></pre>
|
|
<p>最后,为了阻止对指数的赋值,就可以将这些索引签名置为只读(Finally, you can make index signatures readonly in order to prevent assignment to their indices):</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> ReadonlyStringArray {
|
|
readonly [index: <span class="hljs-built_in">number</span>]: <span class="hljs-built_in">string</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> myArray: ReadonlyStringArray = [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>];
|
|
<span class="hljs-comment">//Index signature in type 'ReadonlyStringArray' only permits reading. (2542)</span>
|
|
myArray[<span class="hljs-number">2</span>] = <span class="hljs-string">"Mallory"</span>;
|
|
</code></pre>
|
|
<p>因为此处的索引签名是只读的,因此这里就不能设置<code>myArray[2]</code>了。</p>
|
|
<h2 id="类的类型(class-types)">类的类型(Class Types)</h2>
|
|
<h3 id="应用某个接口(implementing-an-interface)">应用某个接口(Implementing an interface)</h3>
|
|
<p>在诸如C#及Java这样的语言中,接口的一种最常用方式,就是显式地强调某个类满足一种特定的合约,那么在TypeScript中,这样做也是可能的。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> ClockInterface {
|
|
currentTime: <span class="hljs-built_in">Date</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> Clock <span class="hljs-keyword">implements</span> ClockInterface {
|
|
currentTime: <span class="hljs-built_in">Date</span>;
|
|
<span class="hljs-keyword">constructor</span> (h: number, m: number) {}
|
|
}
|
|
</code></pre>
|
|
<p>在接口中还可以对将在类中应用到的方法进行描述,就像下面示例中对<code>setTime</code>所做的那样:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> ClockInterface {
|
|
currentTime: <span class="hljs-built_in">Date</span>;
|
|
setTime (d: <span class="hljs-built_in">Date</span>);
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> Clock <span class="hljs-keyword">implements</span> ClockInterface {
|
|
currentTime: <span class="hljs-built_in">Date</span>;
|
|
|
|
setTime (d: <span class="hljs-built_in">Date</span>) {
|
|
<span class="hljs-keyword">this</span>.currentTime = d;
|
|
}
|
|
|
|
<span class="hljs-keyword">constructor</span> (h: number, m: number) {}
|
|
}
|
|
</code></pre>
|
|
<p>接口对类的公共侧进行了描述,而不是同时描述公共及私有侧。这就禁止对使用接口来对同时有着特定类型的该类实例的私有面的类,进行检查(Interfaces describe the public side of the class, rather than both the public and private side. This prohibits you from using them to check that a class also has particular types for the private side of the class instance)。</p>
|
|
<h3 id="类的静态与实例侧(difference-between-the-static-and-instance-sides-of-classes)">类的静态与实例侧(Difference between the static and instance sides of classes)</h3>
|
|
<p>在与类一同使用接口是时,记住类有着两种类型:静态侧的类型与示例侧的类型(the type of the static side and the type of the instance side),是有帮助的。或许已经注意到在使用构建签名来建立一个接口,并尝试应用此接口来建立类的时候,将报出一个错误:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> ClockInterface {
|
|
<span class="hljs-keyword">new</span> (hour: <span class="hljs-built_in">number</span>, minute: <span class="hljs-built_in">number</span>);
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> Clock <span class="hljs-keyword">implements</span> ClockInterface {
|
|
currentTime: <span class="hljs-built_in">Date</span>;
|
|
<span class="hljs-keyword">constructor</span> (h: number, m: number) {}
|
|
}
|
|
</code></pre>
|
|
<p>这是因为在某个类应用某个接口时,仅有该类的实例侧被检查了。因为该构建器位处静态侧,所以其并不包含在此检查中。</p>
|
|
<p>那么就需要直接在该类的静态侧上动手了。在此实例中,定义了两个接口:用于构建器的<code>ClockConstrutor</code>与用于实例方法的<code>ClockInterface</code>。随后为便利起见,这里定义了一个构建器函数<code>createClock</code>,以创建出传递给它的该类型的实例。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> ClockConstrutor {
|
|
<span class="hljs-keyword">new</span> (hour: <span class="hljs-built_in">number</span>, minute: <span class="hljs-built_in">number</span>): ClockInterface;
|
|
}
|
|
|
|
<span class="hljs-keyword">interface</span> ClockInterface {
|
|
tick();
|
|
}
|
|
|
|
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createClock</span> (<span class="hljs-params">ctor: ClockConstrutor, hour: <span class="hljs-built_in">number</span>, minute: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">ClockInterface</span> </span>{
|
|
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ctor (hour, minute);
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> DigitalClock <span class="hljs-keyword">implements</span> ClockInterface {
|
|
<span class="hljs-keyword">constructor</span> (h: number, m: number) {}
|
|
|
|
tick () {
|
|
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"beep beep"</span>);
|
|
}
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> AnalogClock <span class="hljs-keyword">implements</span> ClockInterface {
|
|
<span class="hljs-keyword">constructor</span> (h: number, m: number) {}
|
|
|
|
tick () {
|
|
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"tick tock"</span>);
|
|
}
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> digital = createClock (DigitalClock, <span class="hljs-number">12</span>, <span class="hljs-number">17</span>);
|
|
<span class="hljs-keyword">let</span> analog = createClock (AnalogClock, <span class="hljs-number">7</span>, <span class="hljs-number">32</span>);
|
|
</code></pre>
|
|
<p>因为<code>createClock</code>第一个参数是<code>ClockConstrutor</code>, 那么在<code>createClock(AnalogClock, 7, 32)</code>中,它就对<code>AnalogClock</code>有着正确的构建签名进行检查。</p>
|
|
<h2 id="扩展接口(extending-interfaces)">扩展接口(Extending Interfaces)</h2>
|
|
<p>与类一样,接口也可以相互扩展。此特性令到将某接口的成员拷贝到另一接口可行,这就在将接口分离为可重用组件时,提供更多的灵活性。</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Shape {
|
|
color: <span class="hljs-built_in">string</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">interface</span> Square <span class="hljs-keyword">extends</span> Shape {
|
|
sideLength: <span class="hljs-built_in">number</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> square = <Square> {};
|
|
square.color = <span class="hljs-string">"blue"</span>;
|
|
square.sideLength = <span class="hljs-number">10</span>;
|
|
</code></pre>
|
|
<p>一个接口还可以对多个接口进行扩展,从而创建出所有接口的一个联合(a combination of all of the interfaces):</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Shape {
|
|
color: <span class="hljs-built_in">string</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">interface</span> PenStroke {
|
|
penWidth: <span class="hljs-built_in">number</span>;
|
|
}
|
|
|
|
|
|
<span class="hljs-keyword">interface</span> Square <span class="hljs-keyword">extends</span> Shape, PenStroke {
|
|
sideLength: <span class="hljs-built_in">number</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> square = <Square> {};
|
|
square.color = <span class="hljs-string">"blue"</span>;
|
|
square.sideLength = <span class="hljs-number">10</span>;
|
|
square.penWidth = <span class="hljs-number">5.0</span>;
|
|
</code></pre>
|
|
<h2 id="混合类型(hybrid-types)">混合类型(Hybrid Types)</h2>
|
|
<p>正如早先所提到的那样,接口具备描述存在于真实世界JavaScript中的丰富类型(As we mentioned earlier, interfaces can describe the rich types present in real world JavaScript)。由于JavaScript的动态且灵活的天性,因此偶尔会遇到某个对象将以结合上述各种类型的方式运作的情况。</p>
|
|
<p>这类实例之一,就是某个对象同时以函数与对象,并带有一些属性方式行事:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Counter {
|
|
(start: <span class="hljs-built_in">number</span>): <span class="hljs-built_in">string</span>;
|
|
interval: <span class="hljs-built_in">number</span>;
|
|
reset(): <span class="hljs-built_in">void</span>;
|
|
}
|
|
|
|
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCounter</span> (<span class="hljs-params"></span>): <span class="hljs-title">Counter</span> </span>{
|
|
<span class="hljs-keyword">let</span> counter = <Counter> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">start: <span class="hljs-built_in">number</span></span>) </span>{};
|
|
counter.interval = <span class="hljs-number">123</span>;
|
|
counter.reset = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{};
|
|
<span class="hljs-keyword">return</span> counter;
|
|
}
|
|
|
|
<span class="hljs-keyword">let</span> c = getCounter();
|
|
c(<span class="hljs-number">10</span>);
|
|
c.reset();
|
|
c.interval = <span class="hljs-number">5.0</span>;
|
|
</code></pre>
|
|
<p>在与第三方JavaScript(注:TypeScript, 你,别人的程序)交互时,就需要使用上面这样的模式,来充分描述类型的形状(When interacting with 3rd-party JavaScript, you may need to use patterns like the above to fully describe the shape of the type)。</p>
|
|
<h2 id="对类进行扩展的接口(interface-extending-classes)">对类进行扩展的接口(Interface Extending Classes)</h2>
|
|
<p>当某个接口对类类型进行扩展时,它将继承该类的成员,却不继承这些成员的实现(When an interface type extends a class type, it inherits the members of the class but not their implementations)。这就如同接口已经对该类的所有成员进行了声明,而没有提供到其具体实现。接口甚至会继承到某个基类的私有及受保护成员。那就意味着在创建某个对带有私有及保护成员的类进行扩展的接口时,所建立的接口类型,就只能被被扩展的类所其子类所应用(实现,It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. This means that when you create an interface that extends a class with private or protected members, that interface type can only be implemented by that class or a subclass of it)。</p>
|
|
<p>在有着大的继承层次时,此特性是有用的,但需要指出的是,这只在代码中有着仅带有确定属性的子类时才有用(This is useful when you have a large inheritance hierarchy, but want to specify that your code works with only subclass that have certain properties)。这些子类除了继承自基类外,不必是有关联的。比如:</p>
|
|
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Control {
|
|
<span class="hljs-keyword">private</span> state: <span class="hljs-built_in">any</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">interface</span> SelectableControl <span class="hljs-keyword">extends</span> Control {
|
|
select (): <span class="hljs-built_in">void</span>;
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> Button extends Control <span class="hljs-keyword">implements</span> SelectableControl {
|
|
select () {}
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> TextBox extends Control {}
|
|
|
|
<span class="hljs-comment">//Class 'Image' incorrectly implements interface 'SelectableControl'.</span>
|
|
<span class="hljs-comment">//Property 'state' is missing in type 'Image'. (2420)</span>
|
|
<span class="hljs-keyword">class</span> Image <span class="hljs-keyword">implements</span> SelectableControl {
|
|
select () {}
|
|
}
|
|
|
|
<span class="hljs-keyword">class</span> Location {}
|
|
</code></pre>
|
|
<p>在上面的示例中,<code>SelectableControl</code>包含了所有<code>Control</code>的成员,包括私有的<code>state</code>属性。因为<code>state</code>是一个私有成员,因此对于<code>Control</code>的后代,就只可能去应用<code>SelectableControl</code>这个接口了。这是因为只有<code>Control</code>的后代,才会有着这个源自同一声明的<code>state</code>私有成员,这也是私有成员可用的一个要求(Since <code>state</code> is a private member it is only possible for descendants of <code>Control</code> to implement <code>SelectableControl</code>. This is because only descendants of <code>Control</code> will have a <code>state</code> private member that originates in the same declaration, which is a requirement for private members to be compatible)。</p>
|
|
<p>在<code>Control</code>这个类中,通过<code>SelectableControl</code>的某个实例去访问<code>state</code>这个私有成员,是可能的。同时,某个<code>SelectableControl</code>也会与一个已知有着<code>select</code>方法的<code>Control</code>那样行事(Effectively, a <code>SelectableControl</code> acts like a <code>Control</code> that is known to have a <code>select</code> method)。这里的<code>Button</code>与<code>TextBox</code>都是<code>SelectableControl</code>的子类型(因为它们都是继承自<code>Control</code>,并有着<code>select</code>方法), 但<code>Image</code>与<code>Location</code>就不是了。</p>
|
|
|
|
|
|
</section>
|
|
|
|
</div>
|
|
<div class="search-results">
|
|
<div class="has-results">
|
|
|
|
<h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
|
|
<ul class="search-results-list"></ul>
|
|
|
|
</div>
|
|
<div class="no-results">
|
|
|
|
<h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
|
|
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
</div>
|
|
</div>
|
|
|
|
</div>
|
|
|
|
|
|
|
|
<a href="03_classes.html" class="navigation navigation-prev " aria-label="Previous page: 类">
|
|
<i class="fa fa-angle-left"></i>
|
|
</a>
|
|
|
|
|
|
<a href="05_functions.html" class="navigation navigation-next " aria-label="Next page: 函数">
|
|
<i class="fa fa-angle-right"></i>
|
|
</a>
|
|
|
|
|
|
|
|
</div>
|
|
|
|
<script>
|
|
var gitbook = gitbook || [];
|
|
gitbook.push(function() {
|
|
gitbook.page.hasChanged({"page":{"title":"接口","level":"1.5","depth":1,"next":{"title":"函数","level":"1.6","depth":1,"path":"05_functions.md","ref":"05_functions.md","articles":[]},"previous":{"title":"类","level":"1.4","depth":1,"path":"03_classes.md","ref":"03_classes.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":["livereload"],"pluginsConfig":{"livereload":{},"highlight":{},"search":{},"lunr":{"ignoreSpecialCharacters":false,"maxIndexSize":1000000},"sharing":{"weibo":false,"all":["facebook","google","twitter","weibo","instapaper"],"google":false,"twitter":true,"vk":false,"instapaper":false,"facebook":true},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css","pdf":"styles/pdf.css","epub":"styles/epub.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css","pdf":"styles/pdf.css","epub":"styles/epub.css"}},"file":{"path":"04_interfaces.md","mtime":"2019-04-03T06:43:16.308Z","type":"markdown"},"gitbook":{"version":"3.2.3","time":"2019-04-04T00:04:23.982Z"},"basePath":".","book":{"language":""}});
|
|
});
|
|
</script>
|
|
</div>
|
|
|
|
|
|
<script src="gitbook/gitbook.js"></script>
|
|
<script src="gitbook/theme.js"></script>
|
|
|
|
|
|
<script src="gitbook/gitbook-plugin-livereload/plugin.js"></script>
|
|
|
|
|
|
|
|
<script src="gitbook/gitbook-plugin-search/search-engine.js"></script>
|
|
|
|
|
|
|
|
<script src="gitbook/gitbook-plugin-search/search.js"></script>
|
|
|
|
|
|
|
|
<script src="gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
|
|
|
|
|
|
|
|
<script src="gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
|
|
|
|
|
|
|
|
<script src="gitbook/gitbook-plugin-sharing/buttons.js"></script>
|
|
|
|
|
|
|
|
<script src="gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
|
|
|
|
|
|
|
|
</body>
|
|
</html>
|
|
|