在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
像基本的JavaScript一样,TypeScript支持numbers, strings, structures, boolean等基本类型,而扩展的enum等类型,为编程提供了更多帮助。 这是最简单的类型 var isDone: boolean = false; Numbervar height: number = 6; Stringvar name: string = "bob"; name = 'smith'; Arrayvar list:number[] = [1, 2, 3]; var list:Array<number> = [1, 2, 3]; Enum枚举enum Color {Red, Green, Blue}; var c: Color = Color.Green; enum Color {Red = 1, Green, Blue}; var c: Color = Color.Green; enum Color {Red = 1, Green = 2, Blue = 4}; var c: Color = Color.Green; enum Color {Red = 1, Green, Blue}; var colorName: string = Color[2]; alert(colorName); Anyvar notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean var list:any[] = [1, true, "free"]; list[1] = 100; Voidfunction warnUser(): void { alert("This is my warning message"); } 接口我们的第一个Interfacefunction printLabel(labelledObj: {label: string}) { console.log(labelledObj.label); } var myObj = {size: 10, label: "Size 10 Object"}; printLabel(myObj); interface LabelledValue { label: string; } function printLabel(labelledObj: LabelledValue) { console.log(labelledObj.label); } var myObj = {size: 10, label: "Size 10 Object"}; printLabel(myObj); 可选属性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"}); 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; // 这里编译器会进行类型检查 } if (config.width) { newSquare.area = config.width * config.width; } return newSquare; } var mySquare = createSquare({color: "black"}); 函数型接口interface SearchFunc { (source: string, subString: string): boolean; } var mySearch: SearchFunc; mySearch = function(source: string, subString: string) { var result = source.search(subString); if (result == -1) { return false; } else { return true; } } var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { var result = src.search(sub); if (result == -1) { return false; } else { return true; } } |
请发表评论