TypeScript
注意编译Typescript项目之前需要确保安装了node.js
编译.ts文件项目需要打开终端输出tsc index.ts 之后会生成一个index.js文件
// //ts中创建接口使用interface
interface Person {
firstName: string
lastName: string
}
function person(person: Person) {
return `my name is ${person.firstName}${person.lastName}`
}
let user: Person = {
firstName: "wu",
lastName: "huiluo"
}
console.log(person(user))
接下来我们可以声明一个User类来代替let user
//声明一个类
class User {
fullName: string
firstName: string
lastName: string
constructor(firstName: string,lastName: string) {
this.firstName = firstName
this.lastName = lastName
this.fullName = firstName + '' + lastName
}
}
最终代码
//声明一个类
class User {
fullName: string
firstName: string
lastName: string
constructor(firstName: string,lastName: string) {
this.firstName = firstName
this.lastName = lastName
this.fullName = firstName + '' + lastName
}
}
// //ts中创建接口使用interface
interface Person {
firstName: string
lastName: string
}
function person(person: Person) {
return `my name is ${person.firstName}${person.lastName}`
}
let user = new User('wuhui','luo')
console.log(person(user))
在终端中运行ts程序
程序执行结果完美兼容了User类和Person类