相关疑难解决方法(0)

如何理解类型 any、unknown、{} 之间以及它们与其他类型之间的关系?

试图理解类型之间的关系我有这个代码

type CheckIfExtends<A, B> = A extends B ? true : false;

type T1 = CheckIfExtends<number, unknown>; //true
type T2 = CheckIfExtends<number, {}>; //true
type T3 = CheckIfExtends<number, any>; //true
type T4 = CheckIfExtends<() => void, unknown>; //true
type T5 = CheckIfExtends<() => void, {}>; //true
type T6 = CheckIfExtends<() => void, any>; //true
type T7 = CheckIfExtends<unknown, any>; //true
type T8 = CheckIfExtends<any, unknown>; //true
type T9 = CheckIfExtends<{}, unknown>; //true
type T10 = CheckIfExtends<{}, any>; //true
type T11 …
Run Code Online (Sandbox Code Playgroud)

types typescript

6
推荐指数
1
解决办法
411
查看次数

没有参数的传递函数不会引发错误

我正在使用 TypeScript 4.3.5。在代码中,我需要传递一个函数,我需要检查该函数是否包含必需的参数。此代码不会引发语法错误:

function functionA (call: (name: string) => boolean) {
  call("")
}

function functionB () {
  return true;
}

function functionC() {
  functionA(functionB); // this doesn't throw a syntax error
  functionB(""); // this throws a syntax error
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过这种类型定义:

type FunctionB = {
  (name: string): boolean
}
Run Code Online (Sandbox Code Playgroud)

没有任何效果。我希望 TypeScript 在调用时抛出语法错误,functionA(functionB)因为 functionB 不包含预期的参数。当我调用functionB("")它时会引发错误。

有什么解决方案可以在我调用时遇到语法错误functionA(functionB)吗?

typescript

3
推荐指数
2
解决办法
112
查看次数

标签 统计

typescript ×2

types ×1