1. unknown is the parent type of all types, other types can be assigned to unknown
let a: undefined = undefined;
let b: null = null;
let x2: unknown;
x2 = a; //正确
x2 = b; //正确
2. never is a subtype of any type and can be assigned to any type
let a: undefined = undefined;
let b: null = null;
function err(): never { // OK
throw new Error('error');
}
a = err(); //正确
b = err(); //正确
3. Any can be assigned to any type, and any type can be assigned to any, except that any cannot be assigned to never (but never can be assigned to any)
let a: undefined = undefined;
let b: null = null;
let err: never;
let y: any = 4;
a = y; //正确
b = y; //正确
y = a; //正确
y = b; //正确
err = y ; //报错 不能将类型“any”分配给类型“never”。ts(2322)
4. Subtypes can be assigned to supertypes. But the supertype cannot be assigned to the subtype, an assertion must be added
let v: void;
let a: undefined = undefined;
v = a; //正确
a = v; //错误 不能将类型“void”分配给类型“undefined”。ts(2322)
a = v as undefined; //正确
5. The unknown type can accept any value, but cannot operate (to assert or add conditional judgment);
any type, can accept any value, and can also operate (unsafe, will report an error)
So usually, if a method or component's property, what type is defined, and what type we pass in, it's done, why do we need to organize this picture?
Because we sometimes can't define a type very precisely, we just want to pass in a subtype so that it can also be recognized.
For example, in vue:
<xx-upload :before-load="handleBeforeLoad">
//setup ts代码
let handleBeforeLoad = ()=>{
}
This will report an error, because you will find that the type passed in before-load is a custom type defined by the namespace.
Either you pass in exactly the type that matches
import type { UploaderBeforeRead } from "xx/lib/upload/types"
let beforeRead:UploaderBeforeRead = (file:File | File[]):boolean=>{
}
Either pass in an any and receive an any parameter, because "any can be assigned to any type, and any type can be assigned to any" in the third clause can be solved.
let beforeRead:any = (file:any):boolean=>{
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。