Closed liuben-team closed 1 day ago
文档地址
// 写法一 const assertIsNumber = (value: unknown): asserts value is number => { if (typeof value !== 'number') throw Error('Not a number'); }; assertIsNumber(1)
tsconfig.json ("typescript": "^5.6.2")
tsconfig.json
{ "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 } }
网上有一些说法是:为了确保类型断言函数在使用箭头函数定义时能够正确工作,我们需要确保类型断言函数的定义包含显式的类型注解。并给出下面的解决方案,报错依然存在
const n: unknown = 1; assertIsNumber(n)
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAhhCBTATlAkhAcgVwLYBGqMAvDABQBQMMAbnADY5IBcOYA1mCAO5iUBKFgmRoIdRsxgBLcWHxEUpAHwwA3tRkAzClACeAByQgd9JkhgBCEmQDk8wqlsDNNKAAsUvGAFEUXlHJbLBBYOBgHRWcAbkoAX2igA
参考 https://github.com/microsoft/TypeScript/pull/33622#issuecomment-575301357 ,删除写法一。
文档地址
tsconfig.json
("typescript": "^5.6.2")