鸿蒙开发TypeScript第二课:类型系统
·
鸿蒙开发TypeScript第二课:类型系统
类型系统,学以下6种即可,记住都是小写的
boolean
string
number
object
undefined
null
第二课关键点:学好6种基础类型
直接上代码:
/**
* 第二课:类型系统,学以下6种即可,记住都是小写的
* boolean
string
number
object
undefined
null
联合类型用|联合类型起来:boolean|string 任何一个类型只要属于A或B
交叉类型用&符号:很少使用,比如boolean&string,一个类型既是boolean又是string,显然是不存在的。
(鸿蒙不支持交叉类型,可以不学,要用extends方式把多个类型继承下来)
typeof运算符是一个一元运算符,返回一个字符串,代表操作数的类型
类型的兼容:如果类型A的值可以赋值给类型B,那么类型A就称为类型B的子类型
规则:凡是可以使用父类型的地方,都可以使用子类型
*/
@Entry
@Component
struct Lesson_2_type_system_Page {
@State message: string = 'lesson_2_type_system_Page';
j?:number // 声明了,没有赋值,看看它的值是什么
aboutToAppear(): void {
// 1、boolean
let flag :boolean = false
flag = true
// 2、string
let name:string = "张三"
// 大家好,我是张三。用的是模板字符。先是ESC下面的按键,再用美元符合括起来你的变量
name = `大家好,我是${name}`
// 3、number (它是包括了整数和小数的值)
let count:number = 100
count = 88.5
// 4、object:所有对象、数组和函数
let x:Person = {
age: 123,
type: 'Person'
} // 鸿蒙要求是对象要明确class或者interface
let y:object = [1, 2, 3]
let z:object = (n:number) => n + 1
let s:Object = 1 // 无所不包的Object类型既不符合直觉,也不方便使用
//let s1:object = 1 // 小写的就不行
// 5、undefined 它既是类型也是值,变量或者方法声明了,但是没赋值,它就是undefined
let i:undefined //它只能赋值undefined了,实际不会这样定义的,没有任何意义
logContent("congge2",`${typeof this.j === 'undefined'}`)
// 6、null 变量和方法不可能null的,是人为赋值null才会null
let n:null = null // 实际不会这样定义的,没有任何意义
let m:Person|null = null // 变量类型必须包含 null 才能赋值 null
// 7、联合类型
let aa:string|number;
aa = 123; // 正确
aa = 'abc'; // 正确
// 那联合类型一般怎么使用呢
// 用typeof把类型判断出来再操作
// 8、typeof
typeof undefined // "undefined"
logContent("conggeTypeof1",`${typeof undefined}`)
typeof this.j // "undefined" 没有赋值
logContent("conggeTypeof2",`${typeof this.j}`)
typeof true // "boolean"
logContent("conggeTypeof3",`${typeof true}`)
typeof 666; // "number"
logContent("conggeTypeof4",`${typeof 666}`)
typeof "张三"; // "string"
logContent("conggeTypeof5",`${typeof "张三"}`)
typeof x; // "object" 而不是 “Person”,因为typeof只能判断出。那怎么才能判断出"Person"呢,可以在Person里面加个type
logContent("conggeTypeof6",`${typeof x}`)
logContent("conggeTypeof7",`${x.type}`)
typeof this.addNum(); // "undefined"
logContent("conggeTypeof8",`${typeof this.addNum()}`)
// 类型兼容
let a1:number|string = "李四"
let a2:number = 123
a1 = a2
教程项目的全部源码图:

有需要完整教程demo的私信我,我每天都看私信的。
更多推荐



所有评论(0)