How to check if type (not object) has a specific property?

  Kiến thức lập trình

I am working with a generated complex type that is rather big. I need to check if certain properties exists on the type with create a variable and initializing all its properties to default/null values, since that would be too much work.

Is there a way to check if properties exists directly on type without instantiating them or creating a variable with all its properties and checking against it?
ex:
Assuming I have the following

    export type Mutations {
        upsertItem: {},
        upsertItemMany: {},
        removeItem: {},
        removeItemMany: {},
        upsertCustomer: {},
        upsertCustomerMany: {},
        removeCustomer: {},
        removeCustomerMany: {},
        ... (1000+ more properties exist)
    }

I tried to do something like:

    var mutations: Mutations;
    Object.hasOwn(mutations, 'upsertItem');

But all I get is the following error:
“Cannot convert undefined or null to object”

and if I try to initialize the variable like

    let mutations: Mutation = {};

I get an error that I need to specify all its properties which defeats the purpose.

I am guessing this can be solved using reflections but I don’t know how.

New contributor

buggyCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

The short answer is, you cannot.

A good thing to remember about Typescript is that is is only a compile-time thing. None of the typescript stuff will be present at runtime. This includes the type construct.

What you are trying, is to perform a runtime check but that will not be possible as the code simply does not know anything related to typescript after it is compiled and when it runs. It’s just plain javascript

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT