質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

Q&A

解決済

1回答

1128閲覧

TypeScriptのIndex Signatureで参照する値がundefinedかどうかを調べる方法が分かりません。

Harineko

総合スコア1

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

0グッド

0クリップ

投稿2021/08/26 09:30

編集2021/08/26 09:54

前提・実現したいこと

TypeScriptとReactでウェブアプリを作っています。
Index Signatureで取得したオブジェクトの値の型がundefinedかどうかをチェックしたいです。

発生している問題・エラーメッセージ

コード中の prevState[contentKey] の型をifでチェックしているのに、IDEから警告を受けてしまいます。

TS2461: Type 'string[] | undefined' is not an array type.

該当のソースコード

質問に無関係なコードは // ... で省略しています。

TypeScript

1// prevState[contentKey] !== undefined としているのに prevState[contentKey] の型が array<string> | undefined と判定される 2 const [content, setContent] = useState<ContentData>(defaultContent); 3 // ... 4 const uploadFiles = (files: ExtendedFile[], contentKey: contentArrayKey, // ... 5 // ... 6 setContent((prevState: ContentData) => { 7 if (prevState[contentKey] !== undefined) { 8 // ここの prevState[contentKey] でエラーが発生しています 9 return ({...prevState, [contentKey]: [...prevState[contentKey], path]}) 10 } 11 return prevState 12 }) 13 // ... 14 15 16// 以下は上で使用したInterfaceです 17export type contentArrayKey = "thumbnailsPath" | "trialBookPath" | "bookPath" | "thumbnailsUrl" | "trialBookUrl"; 18 19export interface ContentData { 20 [key: string]: undefined | (string | number | Array<string> | firebase.firestore.DocumentReference | firebase.firestore.Timestamp), 21 // ... 22 thumbnailsPath: Array<string>; 23 // ... 24 thumbnailsUrl?: Array<string>; 25 trialBookUrl?: Array<string>; 26 // ... 27 trialBookPath?: Array<string>; 28 bookPath?: Array<string>; 29 // ... 30 31 32// 以下は上で使用した定数です。 33export const defaultContent : ContentData = { 34 ref: undefined, authorRef: undefined, bookUrl: undefined, contentId: getRandomId(10), createdAt: timeStamp, updatedAt: timeStamp, 35 appStoreUrl: "", 36 bookPath: new Array<string>(), 37 category: "", 38 description: "", 39 macInstallerPath: "", 40 playStoreUrl: "", 41 price: 0, 42 thumbnailsPath: new Array<string>(), 43 thumbnailsUrl: new Array<string>(), 44 trialBookPath: new Array<string>(), 45 trialBookUrl: new Array<string>(), 46 windowsInstallerPath: "", 47 browserUrl: "", 48 title: "", 49 visibility: "private", 50}

試したこと

ContentDataインターフェースのシグネチャから undefined を除くと、シグネチャ自身に型不一致(undefinedが存在しない)のエラーが発生する代わりに該当のエラーは消えました。
contentArrayKeyからContentDataインターフェースでオプションになっているキーを除くと該当のエラーは消えました。

補足情報(FW/ツールのバージョンなど)

IDEはWebStorm 2021.2です。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

該当箇所を別の変数にキャストすると解決しました。

TypeScript

1 if (Array.isArray(prevState[contentKey])) { 2 const array = prevState[contentKey] as Array<string>; 3 return ({...prevState, [contentKey]: [...array, path]}) 4 }

投稿2021/08/26 10:16

Harineko

総合スコア1

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

maisumakun

2021/08/26 11:39 編集

ゲッターなどが挟める関係上、「prevState[contentKey]」のようなプロパティ参照は、「アクセスするたびに値が変わりうるもの」としてコンパイルされます。 Array.isArrayの「前」にprevState[contentKey]を変数に受けておけば、Array.isArrayによる型推論が有効となります。
Harineko

2021/08/28 09:32

なるほど、ありがとうございますm(__)m
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問