Home > Mobile >  Can't cast a function inside an object to a type
Can't cast a function inside an object to a type

Time:02-02

I try to cast a function inside an object to a type.

Why does this not work?

export type Validator<TInput> = (
  input: TInput
) => Promise<{ [key: string]: string }>;

const works: Validator<string> = async (input) => {
  return {};
};

const doesNotWork = {
  myFancyProperty: Validator<string> = async (input) => {
    return {};
  }
}

=> 'Validator' only refers to a type, but is being used as a value here.

What's the correct syntax? I've searched and tried for an hour now. Maybe i am to tired.

CodePudding user response:

You can't specify a property type in that way.

Your best bet is to type the object, rather than the property:

const works1: {myFancyProperty: Validator<string>} = {
    myFancyProperty: async (input) => {
        return {};
    },
};

But in rare cases, you might use a type assertion on the value you're assigning:

const works2 = {
    myFancyProperty: (async (input) => {
        return {};
    }) as Validator<string>,
};

Playground link

  •  Tags:  
  • Related