Skip to content

A custom type guard produces unexpected behavior inside a generic function #40990

@mckravchyk

Description

@mckravchyk

TypeScript Version: 4.1.0-insiders.20201007

Search Terms:
type guard generics

Code

interface IndexedObject {
    [key: string]: any
}

/**
 * Check if the value is a "plain" JavaScript object initialized with { } (not instance of any class)
 * 
 * In addition to the runtime check, this function should assert that the 
 * argument matches IndexedObject interface
 * 
 */
const isPlainObject = (value: any): value is IndexedObject => (
    typeof value === 'object'
    && value !== null
    && value.constructor === Object
    && Object.getPrototypeOf(value) === Object.prototype
);

function genericFunction<T>(value: T): T {
    if (isPlainObject(value)) {
        type x = typeof value; // T - not quite right
        return value;
    }

    type x = typeof value; // "never"

    return value;
}

function normalFunction(value: any): void {
    if (isPlainObject(value)) {
        type x = typeof value; // IndexedObject - ok
    }

    type x = typeof value; // any - ok
}

Expected behavior:
Inside genericFunction() in the if block, the type of value should be T & IndexedObject. After the if block, the type of value should be x

Actual behavior:
Inside the genericFunction(), in the if block, type of value is T, and after the if block - type of value is never. It works ok in a non-generic function

Playground Link: https://www.typescriptlang.org/play?ts=4.1.0-insiders.20201007#code/JYOwLgpgTgZghgYwgAgJIgCYQB4QweQCMArCBMZAbwChk7kBtAawgE8AuZAZzClAHMAupzghW1AL7VqAegBUc2nOQBhABZkmyYDGRgNyAG5wANgFcUwLsjjIARAAcTcUHeQApOMYDKCPg4oAexIyClBgMGBTYAAvPGQAdwi1KmQJZAAKEECwkB5RJGRA3VFWZARnLi4ASiVkOvQbDAwI4ECQPUC9AygzcGAAWxQEDQQmABpuq2QYPvI2jq41QLMTDBsq6Ap9OG2DOrgofjMh8GQB3ZGIa3QsXAIQ8m1waHgkOqUZagR2nm0uAAKzlARFITwAvJljOYICIxNVONCLP80JgcHhQaFkOCAHyZWj0MCsBwQYpGUzI8FU5AAcmCYLANIJdAAZCzyTDkABCakgVYmZnINkciwAOh+eV4ZnIgSg2OpmPIguFirAov4EDAAKgORyxIg+BgGSREGq8shqtFDh1YD1JOo1QA3NJZiB5u1kBqQNBgAgAGJzSLtAA8ABUccaKbDkKGETGqIKdJkrECXCBVZGYdUzTR6Hm9PrkNhsQWSWSTY7kDIZPGALTIbIUACOZgiKD4-DUYEFeagmrMUA6FcFUkFRJJRZL49JugrVZrdm9hmgdmkvf7g5FEGdo9d7o62SgFxMAbdQZAmYscNYccMgWA61z9CTGRTwPTjzAl9NOZ7hMLxaQtO5ZRpW1aoncGKfsg9aBEwI5rv+E6AaWM5bmBNalDBRTwRIQA

Comment
I am aware that this is not an ideal use case. "plain object" as I defined it, is not strictly tied to IndexedObject interface - which might cause unexpected problems with types. I have decided to not use a type guard for this function, nevertheless - I wanted to submit this as it seems to be a bug. I could not reproduce a more "generic" example.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions