Skip to content

Commit

Permalink
Merge pull request #883 from yytypescript/feature/859
Browse files Browse the repository at this point in the history
docs: ✏️ strictNullChecksがある場合はnullも代入できることを追記
  • Loading branch information
jamashita authored Sep 6, 2024
2 parents 87a5a93 + 5ea0376 commit 69aefd1
Showing 1 changed file with 34 additions and 7 deletions.
41 changes: 34 additions & 7 deletions docs/reference/values-types-variables/object/optional-property.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,61 @@ sidebar_label: オブジェクト型のオプションプロパティ
TypeScriptで、オブジェクトプロパティのオプショナルを型付けするには、プロパティ名の後ろに`?`を書きます。

```ts twoslash
let size: { width?: number };
type Size = {
width?: number;
};
```

オプションプロパティを持ったオブジェクトの型には、そのオプションプロパティを持たないオブジェクトを代入できます。

```ts twoslash
let size: { width?: number };
type Size = {
width?: number;
};
// ---cut---
size = {}; // OK
const size: Size = {}; // OK
```

また、オプションプロパティの値が`undefined`のオブジェクトも代入できます。

```ts twoslash
let size: { width?: number };
type Size = {
width?: number;
};
// ---cut---
size = { width: undefined }; // OK
const size: Size = {
width: undefined,
}; // OK
```

しかし、オプションプロパティの値が`null`の場合は代入できません。

```ts twoslash
// @errors: 2322
let size: { width?: number };
type Size = {
width?: number;
};
// ---cut---
size = { width: null };
const size: Size = {
width: null,
};
```

ただし`strictNullChecks`を無効にしている場合は`null`も代入できるようになります。

```ts twoslash title="strictNullChecksがfalseの場合"
// @strictNullChecks: false
type Size = {
width?: number;
};
// ---cut---
const size: Size = {
width: null,
};
```

## 関連情報

[オプショナルチェーン (optional chaining)](optional-chaining.md)

[strictNullChecks](../../../reference/tsconfig/strictnullchecks.md)

0 comments on commit 69aefd1

Please sign in to comment.