I was creating a custom pipe when I came across this. Why is the example below valid?
async transform(value: any): Promise<string> {
let fullNameBasedOnPreference: string;
fullNameBasedOnPreference = value.property;
return fullNameBasedOnPreference;
}
Link for reference: https://stackblitz.com/edit/angular-ivy-iphhv3?file=src/app/my-pipe.pipe.ts
CodePudding user response:
I am not sure if you are referring to the fact you can return string as any, or why you can return a string when the return type is Promise<any>
. I.E. Your question would be the same if the return type was Promise.
Assuming the later: the async modifier will cause the return value to be wrapped by the Typescript compiler as a promise*.
*It's probably more complicated than this under the hood, but that's the gist of it.
https://devblogs.microsoft.com/typescript/what-about-async-await/
CodePudding user response:
You are giving the any
type to your value
variable. In fact your telling typescript that all types apply to your value
. So typescript will assume that value.property
is a string
value as it could be for example:
const value = {
property: 'string'
}
That's why it works fine.
I would suggest not using any if you know the structure of your variable. Changes are that a custom type has already been defined that you can reuse. If not, create an Interface
describing the type of your data and import it in your component/service.