我最近遇到了一个关于三元检查number | undefinedvar 的问题undefined,但由于我在编写代码时缺乏注意力,当数字为 0 时,它错误地指责它是未定义的值。
然后,我发现了关于strict-boolean-expressions ESLint 规则。
看起来非常有用和安全,但是,给出这个例子:
const text: string | undefined = stringOrUndefined1 || stringOrUndefined2 || undefined; // the strings can be empty
if (!text) // I was doing it this way to check if the value was falsy. With the new rule, it complains.
return;
if (text === undefined || text === '') // This works, but is 4x the length of the one above. I don't want to write …Run Code Online (Sandbox Code Playgroud) 代码解释了我的问题:
type A = {
a: number,
} | null
// Extract as defined in lib.es5.d.ts
type Extract<T, U> = T extends U ? T : never;
type CustomExtract = A extends null ? A : never;
type Result1 = Extract<A, null> // null
type Result2 = CustomExtract; // never
Run Code Online (Sandbox Code Playgroud)
Extract 和 CustomExtract 是相同的代码,不同之处在于 Extract 是泛型类型。
另外,作为相关示例,string | null不扩展null.
那么,在这个主题中,类型到底是如何工作的呢?我可以想象它可能会为每种类型的联合运行通用类型,然后将所有结果联合起来,但我想要真正的技术定义和工作原理。
在具有repo和用户授权范围的GitHub API v3 中,我可以使用GET /user/orgs(https://developer.github.com/v3/orgs/#list-organizations-for-the-authenticated-user,使用 Octokit REST JS,octokit.orgs.listForAuthenticatedUser()) 并且对于每个组织,获取我可以访问的存储库,GET /orgs/:org/repos( https://developer.github.com/v3/repos/#list-organization-repositories,与 Octokit octokit.repos.listForOrg({ org: orgs.data[i].login }))。
但是,使用相同的身份验证范围(用户和存储库),运行此 Graphql 查询
query getOrgsRepos {
viewer {
organizations(first: 10) {
nodes {
repositories(first: 10) {
nodes {
name
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
退货
{
"data": {
"viewer": {
"organizations": {
"nodes": []
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Graphql Explorer 结果(https://developer.github.com/v4/explorer/),但在我的 JS authed(用户和repo范围)应用程序上运行返回相同的空结果 …