Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
liuben-team opened this issue Sep 23, 2024 · 4 comments
Closed

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

liuben-team opened this issue Sep 23, 2024 · 4 comments

Comments

@liuben-team
Copy link

文档地址

// 写法一
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
Copy link
Author

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

const n: unknown = 1;
assertIsNumber(n)

@ruanyf ruanyf closed this as completed Sep 23, 2024
@ruanyf ruanyf reopened this Sep 23, 2024
@ruanyf ruanyf closed this as completed in b376397 Sep 23, 2024
@ruanyf
Copy link
Contributor

ruanyf commented Sep 23, 2024

参考 microsoft/TypeScript#33622 (comment) ,删除写法一。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants