[TypeScript] - TypeScript官方文档学习笔记-接口-中上(三)
接口
方法类型
通过接口可以定义方法参数和返回类型
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
console.log(mySearch("sdasdasd",'sd'))
参数名可以不同
返回值类型可以不写
参数类型可以省略,TS会推断值类型是否匹配
省略版
let mySearch: SearchFunc;
mySearch = function(src, sub) {
let result = src.search(sub);
return result > -1;
}
索引类型
接口可以指定索引类型,数字或字符串。索引类型为字符串串时,更像是字典。
数组也是对象,有索引值
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
可以同时支持这两种类型的索引器,但从数字索引器返回的类型必须是从字符串索引器返回的类型的一个子类型。这是因为当使用数字进行索引时,JavaScript实际上会在索引成对象之前将其转换为字符串。这意味着用100(数字)做索引和用 “100”(字符串)做索引是一回事,所以两者需要保持一致。
class Animal {
name: string;
}
class Dog extends Animal {
breed: string;
}
// Error: indexing with a numeric string might get you a completely separate type of Animal!
interface NotOkay {
[x: number]: Animal;
[x: string]: Dog;
}
interface Okay {
[x: string]: Animal;
[x: number]: Dog;
}
使用
class Animal {
name: string;
}
class Dog extends Animal {
breed: string;
}
interface Okay {
[x: string]: Animal;
[x: number]: Dog;
}
let dog = new Dog()
dog.name = 'dog啊'
dog.breed = 'what?'
let animal = new Animal()
animal.name = 'Animal啊'
let a: Okay = {'喜':dog,'卡':animal}
//或者a.property形式获取
console.log(a['喜'].name)// dog.breed无法获取,断言获取
虽然字符串索引签名是描述 “字典 “模式的有力方式,但它们也强制要求所有属性与其返回类型相匹配。这是因为字符串索引声明obj.property
也可以作为obj["property"]
。在下面的例子中,name的类型与字符串索引的类型不匹配,类型检查器给出了一个错误。
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
}
interface NumberOrStringDictionary {
[index: string]: number | string;
length: number; // ok, length is a number
name: string; // ok, name is a string
}
只读
interface ReadonlyStringArray {
readonly [index: number]: string;
}
let myArray: ReadonlyStringArray = ["Alice", "Bob"];
myArray[2] = "Mallory"; // error!
还没有评论,来说两句吧...