我有一个检查请求数据以访问api端点的功能。对于每个端点,此特定端点可以有不同的预加载数据。
问题是,对于每个操作,我都需要将请求数据转换为端点数据类型。有没有一种方法可以只对case块范围断言一次?或者我应该采取一些不同的方法。
C:\Users\>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.12.13+hotfix.5, on Microsoft Windows [Version 10.0.18362.535], locale en-IN)
[X] Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/setup/#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, set ANDROID_HOME to that location.
You may also want to add it to your PATH environment variable.
[√] Android Studio (version 3.5)
[!] Connected device
! No devices available
! Doctor found issues in 2 categories.
答案 0 :(得分:2)
根据您的用例的具体情况,您可能对discriminated unions感兴趣:
type Req = { endpoint: "endpoint1", data: string }
| { endpoint: "endpoint3" | "endpoint2", data: number }
const checkRole = (_req: unknown): boolean => {
let req = _req as Req;
switch (req.endpoint) {
case 'endpoint1': {
if (req.data = 'hi') return true
return false;
}
case 'endpoint3':
case 'endpoint2': {
req.data += 1;
req.data *= 1;
req.data -= 1;
if (req.data == 5) return true
}
default: return false
}
}