2017-06-16 12 views
4

私は2つのユニオンタイプを持っています.1つはプロパティを持ち、もう1つは持っていません。私は、そのプロパティの存在をチェックすると、それを絞り込むことができますが、それは動作していないと仮定しました。未定義のプロパティを持つシンプルなTypeScriptユニオンタイプを絞り込むことはできません。

私はthis Playground reproを作成しました。この他のvery similar thingはうまくいくようです。私は組合を間違った方法で使用していますか?

ここでは完全を期すためのコードは次のとおりです。

export interface AuthenticatedProfile { 
    readonly userId: string; 
    readonly name: string; 
} 
export interface AnonymousProfile { 
    readonly userId: undefined; 
    readonly otherProp: string; 
} 
export type Profile = AnonymousProfile | AuthenticatedProfile; 

function handleProfile(prof: Profile) { 
    if (prof.userId) { 
     console.log(prof.name); 
    } 
} 

ありがとう!

答えて

3

あなたは教授パラメータの種類を制限するタイプのガードを使用することができます。

export interface AuthenticatedProfile { 
    readonly userId: string; 
    readonly name: string; 
} 
export interface AnonymousProfile { 
    readonly userId: undefined; 
    readonly otherProp: string; 
} 
export type Profile = AnonymousProfile | AuthenticatedProfile; 

function isAuthenticatedProfile(prof: Profile): prof is AuthenticatedProfile { 
    return (<AuthenticatedProfile>prof).name !== undefined; 
} 

function isAnonymousProfile(prof: Profile): prof is AnonymousProfile { 
    return (<AnonymousProfile>prof).otherProp !== undefined; 
} 

function handleProfile(prof: Profile) { 
    if (isAuthenticatedProfile(prof)) { 
     console.log(prof.name); 
    } else if (isAnonymousProfile(prof)) { 
     console.log(prof.otherProp); 
    } 
} 

あなたはhandbookの高度なタイプ]セクションでtypescriptですタイプガードについての詳細を読むことができます。

+0

あなたの解決策はよく見えます。プロパティuserIdが両方の型の一部であり、それぞれの型が互いに異なる値のセットしか取れない場合、なぜ私の元のチェックの後に型変換が型を推論できないのでしょうか? –

+0

私が 'prof.userId'を呼び出すのは、型ガードなしでうまく動作します。 – toskv

+1

実際には既知の問題であるようです。 https://github.com/Microsoft/TypeScript/issues/12600。なぜあなたはエラーが表示されないのか分からない、それは私が投稿した遊び場のreproのすぐそこにあるprof.userIdにアクセスするその遊び場のリンクでちょうどうまく動作する –

1

次の操作を行うことができます

export interface AuthenticatedProfile { 
    readonly type: "AuthenticatedProfile"; 
    readonly userId: string; 
    readonly name: string; 
} 

export interface AnonymousProfile { 
    readonly type: "AnonymousProfile"; 
    readonly userId: undefined; 
    readonly otherProp: string; 
} 

export type Profile = AnonymousProfile | AuthenticatedProfile; 

function handleProfile(prof: Profile) { 
    if (prof.type === "AnonymousProfile") { 
     console.log(prof.name); // Error 
     console.log(prof.otherProp); // OK 
     console.log(prof.userId); // OK 
    } 
    if (prof.type === "AuthenticatedProfile") { 
     console.log(prof.name); // OK 
     console.log(prof.otherProp); // Error 
     console.log(prof.userId); // OK 
    } 
} 
+0

この代替方法を知っておくとよいですが、値やタイプを変更しない他の解決策に固執します。しかし、私は1つの質問があります。プロパティuserIdが両方の型の一部であり、各型が分離した値のセットしか取れない場合、なぜ元の検査の後に型変換が型を推論できないのですか? –

関連する問題