wangdoc / typescript-tutorial

TypeScript 教程
https://wangdoc.com/typescript
2.43k stars 256 forks source link

断言函数用于函数表达式时,ts 报错, #119

Closed liuben-team closed 1 day ago

liuben-team commented 1 day ago

文档地址

// 写法一
const assertIsNumber = (value: unknown): asserts value is number => {
  if (typeof value !== 'number')
    throw Error('Not a number');
};
assertIsNumber(1)

e2ed5bb2ce6dd0f0d05a975685da0f8

tsconfig.json ("typescript": "^5.6.2")

{
  "compilerOptions": {
    "allowImportingTsExtensions": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "alwaysStrict": true,
    "exactOptionalPropertyTypes": true,
    "module": "NodeNext",
    "moduleResolution": "nodenext",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitOverride": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noPropertyAccessFromIndexSignature": false,
    "noUncheckedIndexedAccess": false,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "strict": true,
    "strictBindCallApply": true,
    "strictFunctionTypes": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": true,
    "target": "ESNext",
    "useUnknownInCatchVariables": false
  }
}
liuben-team commented 1 day ago

网上有一些说法是:为了确保类型断言函数在使用箭头函数定义时能够正确工作,我们需要确保类型断言函数的定义包含显式的类型注解。并给出下面的解决方案,报错依然存在

const n: unknown = 1;
assertIsNumber(n)
ruanyf commented 1 day ago

https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAhhCBTATlAkhAcgVwLYBGqMAvDABQBQMMAbnADY5IBcOYA1mCAO5iUBKFgmRoIdRsxgBLcWHxEUpAHwwA3tRkAzClACeAByQgd9JkhgBCEmQDk8wqlsDNNKAAsUvGAFEUXlHJbLBBYOBgHRWcAbkoAX2igA

liuben-team commented 1 day ago

https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAhhCBTATlAkhAcgVwLYBGqMAvDABQBQMMAbnADY5IBcOYA1mCAO5iUBKFgmRoIdRsxgBLcWHxEUpAHwwA3tRkAzClACeAByQgd9JkhgBCEmQDk8wqlsDNNKAAsUvGAFEUXlHJbLBBYOBgHRWcAbkoAX2igA

image

ruanyf commented 1 day ago

参考 https://github.com/microsoft/TypeScript/pull/33622#issuecomment-575301357 ,删除写法一。