加深TS开发使用,类实现接口

1.实现类,必须实现Car数据接口

/** 定义数据类型 */
interface Car {
    wheel: number;
    color: string;
    say: () => void;
}
type CarProp = {
    wheel: 4 | 6;
    color: string;
}

// 实现一个类,这个类必须实现Car接口
// Class 'MyCar' incorrectly implements interface 'Car'.
//   Type 'MyCar' is missing the following properties from type 'Car': wheel, color, say
class MyCar implements Car {
    wheel: number
    color: string
    // 可以指定数据类型
    constructor(obj: CarProp) {
        this.wheel = obj.wheel
        this.color = obj.color
    }
    say() {
        console.log(`我们的汽车有${this.wheel}个轮胎, 是${this.color}`)
    }

    // 在方法的圆括号后使用: 来指定方法返回的数据类型
    drive(name: string): string {
        return `${name} 有驾驶权限`
        // return 1
    }
}
// Argument of type '8' is not assignable to parameter of type '4 | 6'.
// const myCar = new MyCar(8, '红色') error
// const myCar = new MyCar(6, '红色')
const myCar = new MyCar({wheel: 6, color: '红色'})
myCar.say()
// console.log(myCar.drive(12))
console.log(myCar.drive('张三'))
/********************************************************** 泛型 */
function test<T>(obj: T) {
    if (!!obj) {
        return obj
    } else {
        return {id: 'test'}
    }
}

console.log(test({id: '有传递的值'}))
console.log(test(null))

//tsc 编译

编译后编程js文件

 

 2.命名空间写法

 

 命名空间里是私有写法,外部用不了,只有模块导出export才可以供给外部使用

3.修饰符决定类方法里的 变量私有是否供给外部决定

 

 如果在里面有导入其他文件,则会将其他关联的文件也一并进行了转换js文件,这是摇树机制

posted @ 2022-03-29 20:35  cc-front  阅读(222)  评论(0)    收藏  举报