Skip to content

unknownについての記載を追加 #164

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

Merged
merged 1 commit into from
Sep 12, 2022
Merged
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
7 changes: 6 additions & 1 deletion docs/types/type-assertion.md
Original file line number Diff line number Diff line change
@@ -97,7 +97,7 @@ function handler(event: Event) {
}
```

あなたがその型を依然として必要とするなら、二重アサーションを使うことができますが、最初にすべての型と互換性のある`any`をアサートするので、コンパイラはもう文句を言うことはありません:
あなたがその型を依然として必要とするなら、二重アサーションを使うことができますが、最初にすべての型と互換性のある`unknown`(または`any`)をアサートするので、コンパイラはもう文句を言うことはありません:

```ts
function handler(event: Event) {
@@ -107,3 +107,8 @@ function handler(event: Event) {

#### TypeScriptが単一のアサーションが不十分と判断する方法
基本的に、`S`が`T`のサブタイプであるか `T`が`S`のサブタイプである場合、`S`から`T`へのアサーションは成功します。これは、タイプアサーションを行う際に特別な安全性を提供するためです。完全に任意の型アサーションは非常に安全でない可能性があります。そして、安全でない状態にするために、あなたは`any`を使用する必要があります。

#### `as any as` vs `as unknown as`
両方とも Typescript からすると同じくらい安全ではないです。お好きな方をお使いください。考慮する点としては:
- Linter は `unknown` を好む (`no-explicit-any` ルールを設定している場合)
- `any` は `unknown` よりタイピングする文字数が少ない