Home > Mobile >  TS how can I this function write to a arrow function?
TS how can I this function write to a arrow function?

Time:02-28

How can I write this generic function with a arrow function ?

function simpleState<T>(initial: T): [() => T, (v: T) => void] {
  let value: T = initial;
  return [
    () => value,
    (v: T) => {
      value = v;
    }
  ]
};

CodePudding user response:

const simpleState = <T>(initial: T): [() => T, (v: T) => void] => {
  // same function body as before
}

Since you tagged react-native, be aware that in a .tsx file, this will probably not work, since the <T> will be parsed as being a JSX tag. You can either put it in a .ts file, and import it into a .tsx file, or use one of the following workarounds to get it to not be interpreted as a JSX element.

Trailing comma:

<T,>(initial: T): // etc

Extend from unknown:

<T extends unknown>(initial: T): // etc

CodePudding user response:

const simpleState2 = <T>(initial: T): [() => T, (v: T) => void] => {
  let value: T = initial;
  return [
    () => value,
    (v: T) => {
      value = v;
    },
  ];
}
  • Related