Home > Back-end >  ts return mistake type in not assignable to type
ts return mistake type in not assignable to type

Time:11-09

interface GetAmountProps {
  value: undefined | string
}

const getAmount = (value: GetAmountProps): string => {
  if (value === undefined) return '(0)';

  return value;
};

export default getAmount;

Why do I have an error on the line with return value;?

Type 'GetAmountProps' is not assignable to type 'string'.

Playground

CodePudding user response:

The way you have it defined, a value of value would be:

{
  value: "banana"
}

Notice that this is any object with the property "value" of stype string

You probably meant

type GetAmountProps = undefined | string;

or

const getAmount = ({value}: GetAmountProps): string => {
  if (value === undefined) return '(0)';

  return value;
};

which is called like

getAmount({ value: "banana" });

CodePudding user response:

The function returns a string:

const getAmount = (...): string

For example, when it returns this string literal:

return '(0)'

But then you try to return the variable value:

return value;

Which is not a string:

(value: GetAmountProps)

Perhaps you meant to return its one property, which is a string?:

return value.value;

(As an aside... naming everything "value" is going to cause confusion. Indeed, it already has. You'll want to use more meaningful names.)

  • Related