typescript简单的定义变量

typescript简单的定义变量

// 简单类型定义
const uname: string = 'cyy'
const age: number = 50;
const isParty: boolean = false;
const hobby: any = 'sleep';

// 对象
const person: {
    name: string,
    age: number,
} = {
    name: "cyy",
    age: 50,
};
console.log('对象-->' + person.name); // 输出 cyy

// 接口
interface Person {
    name: string;
    age: number;
}
const cyy: Person = {
    name: "cyy",
    age: 18,
};
console.log('接口-->' + cyy.name); // 输出 cyy

// 数组
const persons: String[] = ["cyy", "cyy1", "cyy2"];
const persons2: (number | string)[] = ["cyy", 2, "cyy2"];
console.log('数组-->' + persons[0]); // 输出 cyy
console.log('数组2-->' + persons2[1]); // 输出 2

// 对象数组
const personList: Person[] = [{
    name: "cyy",
    age: 18,
}, {
    name: "cyy2",
    age: 19,
}];
console.log('对象数组-->>', personList)

// 枚举
enum Color { BrandColor = '#409EFF', Success = '#67C23A', Warning = '#E6A23C', Danger = '#F56C6C', Info = '#909399' };
let c: Color = Color.BrandColor;
console.log('枚举-->' + c); // 输出 #409EFF

// 类
class Car {
    // 字段 
    private engine: string;

    public engine2: string;
    // 构造函数 
    constructor(engine: string, engine2: string) {
        this.engine = engine;
        this.engine2 = engine2;
    }
    get getEngine() {
        return this.engine + "<__";
    }
    set setEngine(engine: string) {
        this.engine = engine
    }
    // 方法 
    disp(): void {
        console.log("发动机为 :   " + this.engine)
    }
}
const car = new Car("v8", "v6");
console.log('类-->' + car.engine2);
console.log('类getEngine-->' + car.getEngine);
car.disp() // 输出 发动机为 xx

// 函数入参
function getTotal(one: number, two: number): number {
    return one + two;
}
const total = getTotal(1, 2);
console.log('函数入参-->' + total); // 输出 3

// 无返回值
function getTotal2(one: number, two: number): void {
    console.log('无返回值-->' + (one + two)); // 输出 3
}
getTotal2(1, 2);

// 对象入参
function getNumber({ one, two }: { one: number, two: number }): number {
    return one + two;
}
const sum = getNumber({ one: 1, two: 2 });
console.log('对象入参-->' + sum); // 输出 3
typescript简单的定义变量
原文链接:,转发请注明来源!

发表评论