[Typescript] asserts tips
typescript Tips
2023-09-14 08:59:12 时间
class SDK {
constructor(public loggedInUserId?: string) {}
createPost(title: string) {
this.assertUserIsLoggedIn();
createPost(this.loggedInUserId, title);
}
assertUserIsLoggedIn(): asserts this is this & { loggedInUserId: string } {
if (!this.loggedInUserId) {
throw new Error("User is not logged in");
}
}
}
Basiclly it is a combination assertion
asserts this is this & { loggedInUserId: string }
Assert this is this, return true
and force loggedInUserId to be string type.
Another way
class SDK {
constructor(public loggedInUserId?: string) {}
createPost(title: string) {
this.assertUserIsLoggedIn(this.loggedInUserId);
createPost(this.loggedInUserId, title);
}
assertUserIsLoggedIn(user: string | undefined): asserts user is string {
if (!user) {
throw new Error("User is not logged in");
}
}
}
I prefer this way better
相关文章
- [Typescript] @typescript-eslint/unbound-method
- [Typescript] 129. Hard - Capitalize Nest Object Keys
- [!Typescript] Tips: dynamic specify the type of arguments to function
- [Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any React component
- [Typescript] Convert a js project to typescript
- [Typescript] Scopes and TypeParams
- [TypeScript] Typescript Intersection & Union Types
- [Typescript] Statically Type Unknown Values with TypeScript's unknown Type
- [Typescript] Simplify iteration of custom data structures in TypeScript with iterators (backwards iteration with for ... of.. loop)
- [TypeScript] Define Custom Type Guard Functions in TypeScript
- [Typescript Kaop-ts] Use AOP in Vue Components with TypeScript and Kaop-ts
- [Typescript] Create a Type-Safe Request Handler with Zod and Express
- [Typescript] 94. Hard - Get Optional
- [Typescript] Tips: Use assertion functions inside classes
- [Typescript] Tips: Assign local variables to default generic slots to dry up your code and improve performance
- [Typescript] Tips: Ensure that all call sites must be given value
- [Typescript] Tips: Create your own 'objectKeys' function using generics and the 'keyof' operator
- [Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any React component
- [Typescript] Tips: Derive a union type from an object
- [Typescript] Convert a js project to typescript
- [Typescript] Statically Type Unknown Values with TypeScript's unknown Type
- [Typescript] Ignore Null or Undefined Values with TypeScript Non-Null Assertion Operator
- [Typescript] Exclude Properties from a Type in TypeScript (Omit)
- [Vue + TS] Create your own Decorators in Vue with TypeScript
- SAP UI5 的 TypeScript 实践
- TypeScript Narrowing 的概念
- 第一章 TypeScript快速入门
- Vue3+TypeScript+Element Plus前端项目构建入门