Typescript中文教程-接口

Home » TypeScript » Typescript中文教程-接口

文章归档

文件夹

Typescript 的一个核心原则是类型检查关注于值的‘类型’。有时被称作‘鸭子类型’(duck typing)或‘结构类型’(structural subtyping)。在typescript里,接口扮演了命名这些类型的角色,同时也是在你的代码和链接你的外部工程里定义链接的有力方法。

1、我们的第一个接口interface

查看接口如何工作的最简单的方法是开始一个简单的实例:

1
2
3
4
5
6
function printLabel(labelledObj: {label: string}) {
  console.log(labelledObj.label);
}
var myObj = {size: 10, label: “Size 10 Object”};
printLabel(myObj);

类型检查将检查调用‘printLable’。‘printLable’函数有一个带有原型‘lable’类型为字符串string的对象参数。需要注意的是我们传入的对象实属性际要比此要多,但是最终编辑器只是检查符合参数要求的那个属性。

我们再写一次同样的例子,这一次使用接口来描述此函数需要一个字符串类型的属性‘lable’:

1
2
3
4
5
6
7
8
9
10
interface LabelledValue {
  label: string;
}
function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}
var myObj = {size: 10, label: “Size 10 Object”};
printLabel(myObj);

接口‘LabledValue’是一个可以用来描述我们前面例子函数需求的名称。它同样要求有一个属性叫做‘lable’并且类型是字符串string。需要注意的是我们不需要像其他语言那样明确的声明我们传入‘printLable’实例的对象。这里主要是‘类型’起到关键作用。如果传入函数的对象符合要求就行。

值得指出的是类型检查器不会要求这些属性按照一定的顺序,只要接口的要求的属性出现并且是正确的类型即可。

2、可选属性

不是接口的所有属性都是必须的。一些存在特定的条件或者可能根本不存在。这些可选的属性在选择袋(option bags),即传入一个函数的只有一个对象,在填补了几个属性时,这种方式很受欢迎。

这里以下面的模式为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface SquareConfig {
  color?: string;
  width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
  var newSquare = {color: “white”, area: 100};
  if (config.color) {
    newSquare.color = config.color;
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}
var mySquare = createSquare({color: “black”});

可选的接口和其他接口类似,只是在每个可选属性里加入‘?’作为属性的声明的一部分。

可选属性的好处是,可以描述可能使用的属性同时捕捉到不应该被使用的属性。例如,我们传入‘createSquare’函数里的属性名字打错啦,编译器将会通知我们一个错误消息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface SquareConfig {
  color?: string;
  width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
  var newSquare = {color: “white”, area: 100};
  if (config.color) {
    newSquare.color = config.collor;  // Type-checker can catch the mistyped name here
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}
var mySquare = createSquare({color: “black”});

 

3、函数类型

接口也能够描述javascript对象包含的更宽范围的‘类型’。在添加一个对象的属性时,接口同样能描述函数的类型。

要用接口描述一个函数的类型,我们给这个接口一个调用签名。这是一个只有参数列表和返回值的函数声明。

1
2
3
interface SearchFunc {
  (source: string, subString: string): boolean;
}

一但我们定义了之后就可以像其他接口一样使用函数类型的接口。这里,我们展示如何通过创建一个函数类型的变量然后设置他的函数值是同样的类型。

1
2
3
4
5
6
7
8
9
10
var mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
  var result = source.search(subString);
  if (result == -1) {
    return false;
  }
  else {
    return true;
  }
}

对于函数类型的正确类型检查来说,参数的名字并不一定要一致。例如我们可以将上面的例子改写成下面这样:

1
2
3
4
5
6
7
8
9
10
var mySearch: SearchFunc;
mySearch = function(src: string, sub: string) {
  var result = source.search(subString);
  if (result == -1) {
    return false;
  }
  else {
    return true;
  }
}

函数的参数检查时每个类型对应参数的位置互相检查。同样我们的函数表达式的返回类型暗示了它返回的值(这里是真或假)。若函数返回的是数字或字符串,类型检查其将通知我们SearchFunc返回值与接口不匹配。

4、数组类型Array Types

跟我们用接口来描述函数类型相似,我们也能描述数组类型。数组类型有一个‘index’类型用来描述允许索引的对象的类型和一个相应的返回类型来访问索引。

1
2
3
4
5
6
interface StringArray {
  [index: number]: string;
}
var myArray: StringArray;
myArray = [“Bob”, “Fred”];

这里有两种索引支持类型,字符串和数字。可以同时支持两种索引形式,但约束数值类型的索引必须是字符类型索引返回类型的子类型。

索引签名是一种非常强有力的描述数组和‘dictionary’模式的方法,同时它也强制所有属性必须符合它的返回类型。在下面这个例子里,属性并没有符合通用索引,类型检查器将返回一个错误:

1
2
3
4
interface Dictionary {
  [index: string]: string;
  length: number;    // error, the type of ‘length’ is not a subtype of the indexer
}

 

5、类类型class types

实现一个接口

在C#或Java等语言里一种最常用的接口是明确地限制一个类符合特定的要求,在typescript里也是可以实现的。

1
2
3
4
5
6
7
8
interface ClockInterface {
    currentTime: Date;
}
class Clock implements ClockInterface  {
    currentTime: Date;
    constructor(h: number, m: number) { }
}

你也可以在一个接口中描述实现类中的方法,我们也用‘setTime’作为例子:

1
2
3
4
5
6
7
8
9
10
11
12
interface ClockInterface {
    currentTime: Date;
    setTime(d: Date);
}
class Clock implements ClockInterface  {
    currentTime: Date;
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}

接口描述类的公共方面而不是其私有方面。这将阻止你用它来检查一个类实例也有特殊的私有方面的类型。

6、静态/实例的类之间的区别

在处理类和接口时,它有助于记住一个类两种类型:静态的类型和实例的类型。您可能会注意到,如果你通过构造签名创建一个接口并尝试创建一个类实现该接口你会得到一个错误:

1
2
3
4
5
6
7
8
interface ClockInterface {
    new (hour: number, minute: number);
}
class Clock implements ClockInterface  {
    currentTime: Date;
    constructor(h: number, m: number) { }
}

这是因为当一个类使用接口时,只检查实例的类。由于构造函数是静态的将不会被检查。

然而,您将需要直接使用类“静态”的一面。在这个例子我们直接使用类:

1
2
3
4
5
6
7
8
9
10
11
interface ClockStatic {
    new (hour: number, minute: number);
}
class Clock  {
    currentTime: Date;
    constructor(h: number, m: number) { }
}
var cs: ClockStatic = Clock;
var newClock = new cs(7, 30);

 

7、扩展接口

就像类,接口可以互相扩展。这个处理的任务复制一个接口的成员到另一个,在你单独的接口为可重用的组件时有更多的自由。

1
2
3
4
5
6
7
8
9
10
11
interface Shape {
    color: string;
}
interface Square extends Shape {
    sideLength: number;
}
var square = <Square>{};
square.color = “blue”;
square.sideLength = 10;

一个接口可以扩展多个接口,创建一个所有组合的接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface Shape {
    color: string;
}
interface PenStroke {
    penWidth: number;
}
interface Square extends Shape, PenStroke {
    sideLength: number;
}
var square = <Square>{};
square.color = “blue”;
square.sideLength = 10;
square.penWidth = 5.0;

 

8、混合型

正如我们前面所提到的,接口可以描述出现在现实世界JavaScript的丰富的类型。由于JavaScript的动态和灵活的性质,你偶尔会遇到一个对象,是上面描述的一些类型的组合。

例子是一个对象,作为一个函数和一个对象的附加属性:

1
2
3
4
5
6
7
8
9
10
interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}
var c: Counter;
c(10);
c.reset();
c.interval = 5.0;

与第三方JavaScript交互,您可能需要使用像上面完全描述的形状类型的模式。

17 Responses to “Typescript中文教程-接口”
  • longchamp

    I am glad for writing to make you know of the beneficial encounter my wife’s child had visiting your web site. She picked up some pieces, which included how it is like to have an incredible teaching mood to have the mediocre ones really easily fully understand a number of extremely tough things. You actually did more than her desires. Thanks for churning out these important, safe, revealing and as well as cool tips about your topic to Lizeth.

    回复
  • gucci belts

    I truly wanted to post a small message to thank you for those wonderful steps you are giving out here. My incredibly long internet investigation has at the end been honored with reliable content to exchange with my great friends. I ‘d declare that we visitors actually are rather lucky to be in a wonderful place with many brilliant individuals with valuable tricks. I feel pretty happy to have discovered your webpages and look forward to some more fun minutes reading here. Thanks once again for all the details.

    回复
  • yeezy boost 350 v2

    I am only commenting to let you be aware of of the outstanding encounter my girl gained visiting yuor web blog. She realized such a lot of pieces, with the inclusion of how it is like to possess a very effective giving mood to make a number of people without problems completely grasp selected very confusing issues. You actually did more than her desires. Thank you for churning out these invaluable, dependable, educational as well as unique tips on your topic to Julie.

    回复
  • pg 1

    I definitely wanted to send a quick message to be able to appreciate you for these great tricks you are giving at this site. My rather long internet search has now been rewarded with wonderful insight to go over with my family. I would admit that most of us visitors actually are really lucky to exist in a wonderful community with many brilliant professionals with interesting hints. I feel pretty grateful to have used your web site and look forward to plenty of more excellent moments reading here. Thank you once more for a lot of things.

    回复
  • nike polo shirts

    I enjoy you because of your own efforts on this website. My mom delights in getting into internet research and it is simple to grasp why. A number of us notice all about the compelling way you make both useful and interesting things by means of this web site and therefore boost response from website visitors on the concern so my simple princess is without a doubt understanding a whole lot. Enjoy the remaining portion of the year. You are always conducting a powerful job.

    回复
  • tory burch outlet

    My husband and i were now thankful that Edward could conclude his basic research through your precious recommendations he received in your web page. It is now and again perplexing to simply happen to be handing out hints which often the others could have been making money from. And we also do know we need you to appreciate for this. The type of explanations you made, the straightforward site navigation, the relationships you will help to instill – it’s mostly amazing, and it is letting our son and the family feel that that theme is thrilling, which is really essential. Many thanks for everything!

    回复
  • adidas tubular shadow

    My wife and i ended up being very excited that Ervin could complete his investigation from the precious recommendations he got using your weblog. It is now and again perplexing to just choose to be giving out instructions which usually other people might have been trying to sell. Therefore we keep in mind we’ve got the blog owner to give thanks to for this. The specific illustrations you’ve made, the simple site navigation, the relationships you can aid to create – it is everything exceptional, and it’s really facilitating our son and us do think this subject is fun, which is particularly serious. Thanks for the whole thing!

    回复
  • curry 5

    I have to get across my respect for your kind-heartedness for men and women that have the need for assistance with your concept. Your special commitment to passing the solution around was especially interesting and have all the time enabled professionals just like me to get to their objectives. Your own warm and helpful advice implies so much a person like me and even more to my office colleagues. Thank you; from all of us.

    回复
  • hermes

    I’m writing to let you know of the beneficial experience my cousin’s child undergone using your blog. She realized a lot of issues, with the inclusion of how it is like to have an awesome coaching character to have the mediocre ones smoothly fully understand several very confusing issues. You undoubtedly exceeded people’s expected results. Thank you for coming up with these helpful, safe, educational and even fun guidance on your topic to Sandra.

    回复
  • golden goose sneakers

    A lot of thanks for your own efforts on this blog. Gloria really likes carrying out investigations and it’s really simple to grasp why. I notice all regarding the lively mode you give worthwhile guides via the web blog and even cause contribution from other individuals about this theme then our own simple princess is actually understanding so much. Have fun with the rest of the new year. You’re the one doing a splendid job.

    回复
  • yeezy boost 350

    I intended to put you one very little word so as to say thank you again considering the marvelous thoughts you have shared at this time. It was quite incredibly generous of people like you to supply openly all many individuals might have made available as an ebook to get some money for their own end, mostly considering the fact that you could have tried it if you ever decided. The solutions as well served to be a fantastic way to realize that other individuals have the same dream much like my own to find out somewhat more in regard to this problem. I think there are many more pleasurable situations up front for individuals who scan through your website.

    回复
  • jordan shoes

    My spouse and i were quite happy that Chris managed to finish off his survey via the precious recommendations he discovered out of your web pages. It’s not at all simplistic just to choose to be giving out thoughts that people may have been selling. And we understand we have the blog owner to appreciate because of that. The entire illustrations you made, the straightforward blog menu, the friendships you can assist to promote – it’s many unbelievable, and it is aiding our son in addition to our family reckon that this content is thrilling, which is pretty serious. Thanks for the whole lot!

    回复
  • cheap mlb jerseys

    Needed to compose you this very small note in order to give many thanks over again with your fantastic strategies you’ve featured in this article. It has been really remarkably open-handed with people like you to grant extensively precisely what most of us might have made available as an ebook to make some profit on their own, particularly given that you might have done it in case you desired. These principles additionally acted as the easy way to realize that other individuals have similar dreams just as my own to realize whole lot more with regards to this problem. I believe there are thousands of more fun instances in the future for folks who looked over your website.

    回复
  • yeezy shoes

    I in addition to my guys were actually reading the excellent pointers located on the website and then all of a sudden I had an awful suspicion I never thanked the web site owner for those tips. Most of the boys were joyful to learn all of them and already have extremely been having fun with these things. Thanks for genuinely so accommodating and also for choosing certain great areas millions of individuals are really needing to be informed on. My honest regret for not expressing appreciation to you sooner.

    回复
  • red bottom shoes

    I’m writing to make you be aware of of the useful experience our daughter undergone visiting your site. She came to find too many issues, with the inclusion of what it’s like to have a marvelous giving character to let other people without difficulty master some extremely tough subject matter. You really did more than people’s expected results. I appreciate you for providing those good, healthy, explanatory and even easy tips on the topic to Gloria.

    回复
  • cheap jordans

    I would like to show my respect for your kind-heartedness giving support to all those that must have assistance with this important field. Your very own commitment to getting the solution across was especially valuable and has really permitted folks much like me to get to their goals. Your own informative information means this much a person like me and even more to my peers. Warm regards; from all of us.

    回复
  • nike roshe run

    Thank you so much for giving everyone remarkably spectacular chance to discover important secrets from this web site. It is usually very superb plus stuffed with fun for me and my office colleagues to visit the blog at the least thrice in one week to find out the fresh tips you have got. Of course, I am actually amazed with your impressive principles you serve. Certain 3 ideas in this post are unquestionably the simplest we have ever had.

    回复

发表评论

Your email address will not be published.