types.ts
export type Hoge =
| {
a: number;
}
| {
b: number;
};
この型からts-auto-guardを使ってtype guard functionを生成すると
types.guard.ts
export function isHoge(obj: unknown): obj is Hoge {
const typedObj = obj as Hoge
return (
((typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
typeof typedObj["a"] === "number" ||
(typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
typeof typedObj["b"] === "number")
)
}
.ts
typedObj["a"]
ここで
TS7053: Element implicitly has an 'any' type because expression of type '"a"' can't be used to index type 'Hoge'. Property 'a' does not exist on type 'Hoge'.
が出てしまう。(typedObj["b"] も同様)
次の様にするとエラーが消える
types.ts
export type Hoge =
| {
a: number;
b: never;
}
| {
a: never;
b: number;
};
types.guard.ts
export function isHoge(obj: unknown): obj is Hoge {
const typedObj = obj as Hoge
return (
((typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
typeof typedObj["a"] === "number" ||
(typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
typeof typedObj["b"] === "number")
)
}