Skip to content

Instantly share code, notes, and snippets.

@keima
Created November 11, 2019 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keima/132b5436a2064c7a75d74fe06f288fe8 to your computer and use it in GitHub Desktop.
Save keima/132b5436a2064c7a75d74fe06f288fe8 to your computer and use it in GitHub Desktop.
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