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.
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>,
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.