像基本的JavaScript一样,TypeScript支持numbers, strings, structures, boolean等基本类型,而扩展的enum等类型,为编程提供了更多帮助。
这是最简单的类型
var isDone: boolean = false;
var height: number = 6;
var name: string = "bob"; name = ‘smith‘;
var list:number[] = [1, 2, 3];
var list:Array<number> = [1, 2, 3];
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);
var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean
var list:any[] = [1, true, "free"]; list[1] = 100;
function warnUser(): void {
alert("This is my warning message");
}
function 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;
}
}
原文:http://www.cnblogs.com/ybst/p/5117871.html