/**
* 泛型
* 在未知类型时可以先用泛型,在调用时再定义返回类型;
* */
//泛型类
class CustomStack<T> {
public push(e:T) {
}
}
// 在使用时定义类型
let c = new CustomStack<string>();
c.push('123');
let c1 = new CustomStack<number>();
c1.push(123);
//泛型函数
function add<I>(x: I) {
return x;
};
add<string>('15');
add<number>(15);
空安全
/**
* 空安全
*
* 默认情况下,ArkTS中的所有类型都是不可为空的,因此类型的值不能为空。这类似于TypeScript的严格空值检查模式(strictNullChecks), 但规则更严格。
*
* */
// let x: number = null; //编译时就会报错了
let x: number | null = null;
x = 1; //ok
x = null; //ok
/**
* 非空断言运算符
*后缀运算符!可用于断言其操作数为非空
* */
class A{
value: number = 0;
}
function foo(a: A | null) {
// a.value; //编译时错误; 无法访问可空值的属性
a!.value; //编译通过, 如果运行时a的值非空, 可以访问到a的属性;如果运算
}
/*
* 空值合并运算符
* 空值合并二元运算符??用于检查左侧表达式的求值是否等于null或者undefined。如果是,则表达式的结果为右侧表达式;否则,结果为左侧表达式。
*
* 换句话说,a ?? b等价于三元运算符(a != null && a != undefined) ? a : b;
* */
class Person{
nick: string | null = null
getNick(): string {
return this.nick ?? '';
}
}