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

feat: assert fn #58

Merged
merged 4 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,8 @@
"editor.formatOnSave": true,
"[sql]": {
"editor.formatOnSave": false
},
"[json]": {
"editor.defaultFormatter": "denoland.vscode-deno"
}
}
10 changes: 10 additions & 0 deletions ts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# TypeScript 相关函数说明

该文件夹内的代码分为三种:

1. 类型.
2. 类型判断函数.
3. 类型断言函数.

类型断言函数在已知 API 结构等场景下非常有用. 类型断言函数不同于普通的 `as` 断言,
`as` 断言一般不会做任何检查, 而类型断言函数而是真的做了一些检查.
17 changes: 17 additions & 0 deletions ts/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,20 @@ export function isUnknownObject(v: unknown): v is UnknownObject {
}
return true;
}

/** 断言为未知对象 */
export function assertUnknownObject(v: unknown): asserts v is UnknownObject {
if (typeof v !== 'object' || v === null) {
throw new TypeError('Expected an object');
}
}

/**
* 断言为数组
* @param v 需要断言的变量
*/
export function assertArray(v: unknown): asserts v is Array<unknown> {
if (!Array.isArray(v)) {
throw new TypeError('Expected an array');
}
}
Loading