我在业务中使用了 TypeScript,但是我在这个网站上再次研究了它,并且我第一次学到了很多东西,所以我决定写一篇带有输出的文章。
我还在阅读网站的开头,所以我会根据需要添加它。

每个 h2 标题都是 Survival TypeScript 中相关页面的链接。
另外,我已经发布了我自己实际尝试过的代码,但它与参考源几乎相同。对不起。

JSON 中 undefined 和 null 的区别

使用 JSON.stringify 转换为 JSON 时删除具有未定义值的属性

const obj = { name: null, age: undefined };

// {"name":null}が出力される
console.log(JSON.stringify(obj));

即使将 JSON 解析为对象,也无法识别 undefined 并出现错误

const str: string = '{"name":null, "age":undefined}';

// エラー:SyntaxError: Unexpected token u in JSON at position 20
console.log(JSON.parse(str));

readonly 和 const 的区别

readonly 禁止赋值给属性,但允许赋值给变量本身。

let obj: { readonly x: number } = { x: 1 };

// エラー:Cannot assign to 'x' because it is a read-only property.
obj.x = 10;

// OK
obj = { x: 100 };

分配给可选属性时的行为

您可以分配未定义的,但不能为空。

let obj: { x: number; y?: number };

// OK
obj = { x: 10, y: undefined };

// エラー:Type 'null' is not assignable to type 'number | undefined'
obj = { x: 10, y: null };

过多的属性检查行为

冗余属性检查仅用于对象字面量赋值。
它不适用于变量赋值。

// エラー:Type '{ x: number; y: number; }' is not assignable to type '{ x: number; }'.
const x: { x: number } = { x: 1, y: 2 };

const xy: { x: number; y: number } = { x: 1, y: 2 };
// OK
const x2: { x: number } = xy;

为什么你应该避免“对象”打字

由于没有关于它具有哪些属性的信息,因此如果您尝试引用这些属性,则会发生错误。

let obj: object = { x: 1, y: 2 };

// エラー:Property 'x' does not exist on type 'object'.
console.log(obj.x);

可以分配任何对象类型。

let obj: object = { x: 1, y: 2 };

// 全てOK
obj = { name: "taro", age: 30 };
obj = [1, 2, 3];
obj = () => {};
obj = /^$/;

可选链

我不知道它也可以用来引用数组和调用函数。

const arr = null;

// エラー:Object is possibly 'null'.
console.log(arr[100]);

// OK
console.log(arr?.[100]);
const func = null;

// エラー:Cannot invoke an object which is possibly 'null'.
console.log(func());

// OK
console.log(func?.());

TypeScript 包含结构子类型

如果签名如下所示相等,则可以相互替换。
此外,在 TypeScript 中,即使继承源不同或一开始没有继承,也可以替换签名是否相同。

class Person {
  constructor(public name: string) {}
}

// 仮に継承元がEmployeeと異なったり、どちらのクラスも継承をしていなくてもシグネチャが同じであればOK
class President extends Person {
  introduce() {
    console.log(`Hi, I'm ${this.name}, a president.`);
  }
}

class Employee extends Person {
  introduce() {
    console.log(`Hi, I'm ${this.name}, an employee.`);
  }
}

// OK
const employee: Employee = new President("taro");

// false
console.log(employee instanceof Employee);
// true
console.log(employee instanceof President);

原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308629830.html

相关文章: