981377660LMT / ts

ts学习
6 stars 1 forks source link

type hierarchy tree #392

Open 981377660LMT opened 1 year ago

981377660LMT commented 1 year ago

image

981377660LMT commented 1 year ago

对称地,该 never 类型的行为类似于顶级类型的反类型 - any 和 unknow ,而 any 和 unknown 接受所有值, never 根本不接受任何值(包括 any 类型的值),因为它是所有类型的子类型。

981377660LMT commented 1 year ago

在许多其他语言(如 C++)中, void 用作函数返回类型,这意味着函数不返回。但是,在 TypeScript 中,对于根本不返回的函数,返回值的正确类型是 never 。 那么 TypeScript 中的类型 void 是什么? void 在TypeScript中是 - undefined TypeScript允许您分配给 undefined void (upcaset),但同样,不是相反(向下投射)。 image

981377660LMT commented 1 year ago

在面向对象编程中,类型转换可以分为两种:向上转型(Upcasting)和向下转型(Downcasting)。

  1. 向上转型(Upcasting):子类转换为父类,这是安全的,因为子类对象可以被看作是父类对象,子类继承了父类的所有属性和方法。例如,如果有一个父类 Animal 和一个子类 Dog,那么 Dog 对象可以被当作 Animal 对象来使用,这就是向上转型。

  2. 向下转型(Downcasting):父类转换为子类,这是不安全的,因为父类对象可能并不是子类对象,父类可能没有子类的一些属性和方法。例如,如果有一个父类 Animal 和一个子类 Dog,那么 Animal 对象不能直接被当作 Dog 对象来使用,需要进行向下转型。在进行向下转型时,通常需要进行类型检查或者捕获可能出现的异常,以确保转型的安全。

981377660LMT commented 1 year ago

situations where TypeScript disallows implicit upcast

TypeScript 不允许隐式上播的情况

通常有两种情况,老实说,发现自己处于这些情况应该非常罕见:

fn({ name: 'foo', key: 1 }) // ❌ Object literal may only specify known properties, and 'key' does not exist in type '{ name: string; }'


- When we assign literal objects directly to variables with explicit types
当我们将字面量对象直接分配给具有显式类型的变量时
```ts
type UserWithEmail = {name: string, email: string}
type UserWithoutEmail = {name: string}

let userB: UserWithoutEmail = {name: 'foo', email: 'foo@gmail.com'} // ❌ Type '{ name: string; email: string; }' is not assignable to type 'UserWithoutEmail'.