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

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

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

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

Q&A

解決済

3回答

1953閲覧

[TypeScript] なぜ型ガードが効かないのでしょう?

TOMIYASU_chan

総合スコア21

TypeScript

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

0グッド

1クリップ

投稿2020/01/02 02:13

編集2020/01/02 02:16

不明な点

以下のfilterByTerm関数内のif文でstringの型ガードが効いて
matchメソッドも使えると考えているのですが、実際はエラーになり
型はインターフェイスでの定義のままの ’string | number ’ となっていて
matchメソッドが無いというエラーが発生しています
これは何が原因なのでしょうか?

TypeScript

1interface Link { 2 description?: string 3 id?: number 4 url: string 5 [index: string]: string | number | undefined 6} 7 8function filterByTerm( 9 input: Array<Link>, 10 searchTerm: string, 11 lookupKey: string = 'url' 12): Array<Link> { 13 if (!searchTerm) throw Error('searchTerm cannot be empty') 14 if (!input.length) throw Error('input cannot be empty') 15 const regex = new RegExp(searchTerm, 'i') 16 return input.filter(function(arrayElement) { 17 if (typeof arrayElement[lookupKey] === 'string') { 18 return arrayElement[lookupKey]!.match(regex) // <-Error 19 } 20 }) 21} 22 23let res = filterByTerm( 24 [{ url: 'string1' }, { url: 'string2' }, { url: 'string3' }], 25 'string3' 26) 27console.log(res)

ErrorMessage

1プロパティ 'match' は型 'string | number' に存在しません。 2 プロパティ 'match' は型 'number' に存在しません。ts(2339)

tsconfig

1{ 2 "compilerOptions": { 3 "target": "es2016", 4 "module": "commonjs", 5 "strict": true, 6 "strictNullChecks": true, 7 "esModuleInterop": true, 8 "declaration": true, 9 "sourceMap": false, 10 "outDir": "./dist/js/" /* Redirect output structure to the directory. */, 11 "rootDir": "./src/", 12 "lib": ["es6", "dom", "es2018", "es2015.iterable","scripthost"], 13 "downlevelIteration": true, 14 "baseUrl": "./", 15 "typeRoots": [ 16 "node_modules/@types", 17 "types/index"], 18 "strictFunctionTypes": false, 19 }, 20}

環境

VS Code 1.41.1
WebPack 4.41.5
typescript 3.7.4
ts-loader 6.2.1
eslint 6.8.0

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

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

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

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

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

guest

回答3

0

1つ考えられることとして、arrayElement[lookupKey]という値は一定だと保証されていません

文法的に、getterで「あるときはstring、あるときはnumberを返す」ようなプロパティを作れてしまう以上、typeof arrayElement[lookupKey] === 'string'をチェックした次の行でarrayElement[lookupKey]がまだ文字列であることは保証されません

いったん変数に受ければ値は固定しますので、それをチェックすればいいでしょう。

typescript

1 return input.filter(function(arrayElement) { 2 const value = arrayElement[lookupKey] 3 if (typeof value === 'string') { 4 return value.match(regex) 5 } 6 })

投稿2020/01/18 01:26

maisumakun

総合スコア145184

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

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

TOMIYASU_chan

2020/01/19 03:59 編集

ありがとうございます。そういったやり方があるのですね・・・if節内の式の評価後のブロック内でもまだ未確定という部分がセマンティクスとしてちょっと不明な感じがしますが、テクニックとしてゲッタからみという観点で他でも役立つと思います。
guest

0

ベストアンサー

https://github.com/microsoft/TypeScript/issues/28081

が(おそらくは)質問の通りのissueで、

Turns out this was just missing. It is super simple to add since it's the same code as property access. I just need to make sure performance is OK.

からの、

Update: The PR is trivial and performance is, as expected, bad for probably-uncommon adversarial code. We need to discuss in the design meeting whether to take this change.

というコメントで閉じられています。

敵対的なコードでパフォーマンス問題があって採用されない(採用するためには設計会議で議論する必要がある)ということのようです。

投稿2020/01/08 01:35

quickquip

総合スコア11038

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

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

TOMIYASU_chan

2020/01/18 01:23 編集

コメントに気がつくのがおそくなりすみません、また、情報ありがとうございます。こんなissueが立ってたのですね。インデックスシグナチャとドット記法との間で以下のようなことまで話されてるとは知りませんでした > We are working in Google internal TS to forbid using the prop access on index signature objects. by Rado Kirov とりあえず、今は以下のようににしています ``` TypeScript return (arrayElement[lookupKey]! as string).match(regex) ```
guest

0

Union 型の値に対しては、共通のプロパティにしかアクセスできません。

If we have a value that has a union type, we can only access members that are common to all types in the union.

https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types

matchstringnumber の共通のプロパティではないです。
こちらに記載のいずれかの方法で、match を呼び出せるかチェックする必要があります。

投稿2020/01/02 04:39

kit494way

総合スコア317

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

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

TOMIYASU_chan

2020/01/03 02:12 編集

ありがとうございます。確かに共用型の場合、共通のものにしかアクセスできないということなのですが、示していただいたハンドブックの例にもありますように、型ガードされたスコープ内では独自のプロパティーにアクセスできていますね。 // Both calls to 'swim' and 'fly' are now okay. if (isFish(pet)) { pet.swim(); } else { pet.fly(); } 型ガード後にはStringのメソッドにアクセスできると思っていましたので、なぜ、まだarrayElement[lookupKey]が共用型のままなのかという部分で疑問です このハンドブックのページありますサンプルで stringの型ガード後のmatchメソッドをコールしても問題はありません function padLeft(value: string, padding: string | number) { if (typeof padding === 'number') { return Array(padding + 1).join(' ') + value } if (typeof padding === 'string') { return padding.match(/.*/) // matchの呼び出し } throw new Error(`Expected string or number, got '${padding}'.`) } }
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問