Created
November 11, 2019 07:08
-
-
Save keima/132b5436a2064c7a75d74fe06f288fe8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class X { | |
id: number = 3 | |
} | |
class Y { | |
id: number = 9 | |
} | |
var x = new X() | |
var y = new Y() | |
function isX(obj: any): obj is X { | |
return obj instanceof X | |
} | |
function isY(obj: any): obj is Y { | |
return obj instanceof Y | |
} | |
function hoge(obj: { id: number }): string { | |
// switchは使えない | |
if (isX(obj)) { | |
return `X: ${obj.id}` | |
} else if (isY(obj)) { | |
return `Y: ${obj.id}` | |
} else { | |
return `?: ${obj.id}` | |
} | |
} | |
console.log() | |
console.log() | |
alert(`${hoge(x)}, ${hoge(y)}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment