0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

type guard function: Element implicitly has an ‘any’ type

Posted at
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")
    )
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?