Typescript : Adding types to a function that takes in a string and returns a different promise based on the string

I have a function that takes in a string and based on the string hits different api’s to fetch images.

I have solved it by writing an interface and then as return type of the function it returns a Promise<Interface> as shown in code below.

    interface IAnimal {
      image?: string | null
      message?: string
      status: string
    }
    const getAnimal = async (inAnimal: string): Promise<IAnimal> => {
      const isDogWord: boolean = ("dog", "Dog", "DOG").includes(inAnimal.trim())
      const isFoxWord: boolean = ("fox", "Fox", "FOX").includes(inAnimal.trim())
      let result: IAnimal = { image: null, status: "tofetch" };
      if(isDogWord) {
        result = await fetch("https://dog.ceo/api/breeds/image/random").then((data) => data.json());
        if(result.status === "success") {
          return {
            image: result.message,
            status: result.status
          }
        }
      }
      if(isFoxWord) {
        result = await fetch("https://randomfox.ca/floof/").then((data) => data.json());
        return {
          image: result.image,
          status: "success"
        }
      }
      return {
        image: null,
        status: "failure"
      }
    };

This solves the typescript errors but i am not happy with making image and message optional in the Interface. I am receiving { "message": "image__link", "status": "success or failure" } from dog api and {"image": "image__link", "status": "success or failure"} from the fox api. Is what i have done the right approach or do we have a better solution.

typescript – Force argument object with a certain key

This seems like something fairly simple, but I have tried searching it multiple ways and couldn’t find an answer.

I want to specify a type for an argument that allows any objects that contain a certain key, like this:

type Action = {type : string};
function reducer(state : object, action : object extends Action) {
    ...
};

Something like this, but this syntax doesn’t work. That is, I want the action argument only to accept objects that contain the key “type” that is a string. If I just do this:

function (state : object, action : {type : string}) {...};

The function only accepts objects that only have the key “type”. How can I achieve this?

Thanks in advance.

javascript – Expected 0 arguments, but got 1 in typescript

//open active panel (and close unactive panels)
const setActivePanel = activePanelNum => {

//remove active class from all the panels
removeClasses(DOMstrings.stepFormPanels, 'js-active');

//show active panel
DOMstrings.stepFormPanels.forEach((elem, index) => {
  if(index === (activePanelNum)) {
    
    elem.classList.add('js-active');
 
    setFormHeight(elem);
    
  }
})

};

If i remove “elem” parameter from setFormHeight(); the code will executed but output has came other than expected.

Please try to help to solve this error.

Thank you in advance.

TypeScript index signature with unknown value

Is there a difference between {(k: string): any} and {(k: string): unknown}. I assumed both would be an object with string key but they are not. The first one accepts any object like value but once the value type is changed from any -> any other type (ex. unknown), it accepts only actual object {}.

I found an answer from @ryan-cavanaugh for the {(k: string): any} part here but the second part confused me.

This is a distinguishing feature between { (k: string): any } and any itself – you can read and write properties of any kind on an object with an index signature

It seems {(k: string): any} is exactly like object type. Can someone please explain to me the difference.

let data: {(n: string): any};

data = (); // Ok
data = () => {}; // Ok
data = new Date(); // Ok
data = Function; // Ok

let data: {(n: string): unknown};

data = {}; // OK
data = (); // Error. But TS handbook says otherwise
data = () => {}; // Error
data = new Date(); // Error
data = Function; // Error

reactjs – React con Javascript y Typescript

Muy buenas a todos!

Actualmente trabajo en un proyecto con react creo que fue creado con npx create-react-app name_project hace dos años. Mi pregunta es si se puede añadir el compilador de typescript a este proyecto con el objetivo de añadir nuevos archivos tipo .tsx a los ya existentes sin modificar los originales.

De antemano, gracias por la ayuda!

javascript – Coverter código Javascrit em Typescript

Alguém poderia me ajudar a converter o código abaixo em um código javascript?

/*===== SHOW NAVBAR  =====*/
const showNavbar = (toggleId, navId, bodyId, headerId) =>{
    const toggle = document.getElementById(toggleId),
    nav = document.getElementById(navId),
    bodypd = document.getElementById(bodyId),
    headerpd = document.getElementById(headerId)

    // Validate that all variables exist
    if(toggle && nav && bodypd && headerpd){
        toggle.addEventListener('click', ()=>{
            // show navbar
            nav.classList.toggle('show')
            // change icon
            toggle.classList.toggle('bx-x')
            // add padding to body
            bodypd.classList.toggle('body-pd')
            // add padding to header
            headerpd.classList.toggle('body-pd')
        })
    }
}

showNavbar('header-toggle','nav-bar','body-pd','header')

/*===== LINK ACTIVE  =====*/
const linkColor = document.querySelectorAll('.nav__link')

function colorLink(){
    if(linkColor){
        linkColor.forEach(l=> l.classList.remove('active'))
        this.classList.add('active')
    }
}
linkColor.forEach(l=> l.addEventListener('click', colorLink))

typescript – Simplifiy the following flow for upload file status tracking

I am using angular and rxjs, and I am doing the following :

I would like to upload an image to GCP, so I need to generate a signed url, upload the image,and while showing status of all the request.

Component => ask a Service A to upload a file.

   this.uploadProgress$ = this.uploadHelperService.uploadImage(userId, image);
   this.subscriptions.add(
      this.uploadProgress$.subscribe((result) => {
        if (result.status !== UploadStatus.SUCCESS) {
          return;
        }
        // Everything worked
      })
    );

Service A => Just bind an API call to generate a signed URL

  uploadImage(userId: string, image: File) {
    const urlGenerator = this.apiService
      .generateUploadUrl({
        userId,
        filename: image.name,
      })
      .pipe(
        map((result) => result.data?.url || ''),
        catchError((e) => throwError(e))
      );

    return this.gcpUploaderService.uploadToGCP(urlGenerator, images(0));
  }

Service B => Generate the URL, and upload the file while tracking the progress.

  uploadToGCP(
    generator$: Observable<string>,
    file: File
  ): Observable<{
    url?: string;
    status: UploadStatus;
  }> {
    return new Observable((subscriber) => {
      subscriber.next({
        status: UploadStatus.INIT,
      });

      generator$.pipe(
        switchMap((url) => {
          subscriber.next({
            status: UploadStatus.UPLOADING,
          });

          return this.httpClient
            .put(url, file, {
              headers: new HttpHeaders({ 'Content-Type': file.type }),
            })
            .pipe(
              map(() => {
                subscriber.next({
                  url,
                  status: UploadStatus.SUCCESS,
                });
                subscriber.complete();
              }),
              catchError((e) => {
                subscriber.next({
                  status: UploadStatus.FAILED,
                });
                subscriber.complete();
                return throwError(e);
              })
            );
        }),
        catchError((e) => {
          subscriber.next({
            status: UploadStatus.FAILED,
          });
          subscriber.complete();
          return throwError(e);
        })
      );
    });
  }

Now all of this works, but it s junky, and I believe can be improved a lot, specially the last part. But I lack of inspiration today.

Typescript how to pass props in parent component

I am practicing typescript. I have error “Type ‘void’ is not assignable to type ‘boolean'” for setAuthenticated(valueFromChild) line and “…is not assignable to type ‘IntrinsicAttributes & { children?: ReactNode; }’.” for all places(,) where I pass props into child components here. How do I fix the errors?

import { FunctionComponent, useState } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Navbar from './Components/navbar.component';
import './App.css';
import { ThemeProvider } from '@material-ui/core/styles';
import theme from './Theme/theme';
import Login from './Components/login.component';
import Register from './Components/register.component';

const App: FunctionComponent = () => {
  const (isAuthenticated, setIsAuthenticated) = useState<boolean>(false);
  const handleAuth = (valueFromChild: boolean): boolean =>
    setIsAuthenticated(valueFromChild);
  return (
    <ThemeProvider theme={theme}>
      <BrowserRouter>
        <Navbar isAuthenticated={isAuthenticated} />
        <Switch>
          <Route
            exact
            path="/login"
            render={(props) => <Login {...props} handleAuth={handleAuth} />}
          />
          <Route
            exact
            path="/register"
            render={(props) => <Register {...props} handleAuth={handleAuth} />}
          />
        </Switch>
      </BrowserRouter>
    </ThemeProvider>
  );
};

export default App;

typescript – Animating Pathfinding Generically

This is part of a project I built to visualise pathfinding algorithms. These files run the algorithms and gather a list of frames, which are used to show the animations.

algorithms.ts

export type Algorithm = (start: Coord, goal: Coord, walls: boolean()(), weights: number()(), heuristic: string) => GridFrame();

export function breadthFirstSearch(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), _: string) {
    const queue = new Queue<Coord>();
    const distances = new HashMap<Coord, number>();

    return genericUnidirectionalSearch(start, goal, queue, distances, weights, walls);
}

export function depthFirstSearch(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), _: string) {
    const stack = new Stack<Coord>();
    const distances = new HashMap<Coord, number>();

    return genericUnidirectionalSearch(start, goal, stack, distances, weights, walls);
}

export function bestFirstSearch(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), heuristic: string) {
    const heuristicComparator = stringToHeuristic.get(heuristic)(goal);
    const priorityQueue = new PriorityQueue(heuristicComparator);
    const distances = new HashMap<Coord, number>();

    return genericUnidirectionalSearch(start, goal, priorityQueue, distances, weights, walls);
}

export function dijkstra(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), _: string) {
    const distances = new HashMap<Coord, number>();
    const distanceComparator = generateDijkstraComparator(distances);
    const priorityQueue = new PriorityQueue(distanceComparator);

    return genericUnidirectionalSearch(start, goal, priorityQueue, distances, weights, walls);
}

export function aStar(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), heuristic: string) {
    const distances = new HashMap<Coord, number>();
    const comparator = generateAStarComparator(goal, distances, heuristic);
    const priorityQueue = new PriorityQueue(comparator);

    return genericUnidirectionalSearch(start, goal, priorityQueue, distances, weights, walls);
}

export function randomSearch(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), _: string) {
    const distances = new HashMap<Coord, number>();
    const comparator = generateRandomComparator();
    const priorityQueue = new PriorityQueue(comparator);

    return genericUnidirectionalSearch(start, goal, priorityQueue, distances, weights, walls);
}

export function bidirectionalBFS(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), _: string) {
    const forwardsDistances = new HashMap<Coord, number>();
    const backwardsDistances = new HashMap<Coord, number>();
    const forwardQueue = new Queue<Coord>();
    const backwardQueue = new Queue<Coord>();

    return genericBidirectionalSearch(forwardQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls);
}

export function bidirectionalDFS(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), _: string) {
    const forwardsDistances = new HashMap<Coord, number>();
    const backwardsDistances = new HashMap<Coord, number>();
    const forwardsStack = new Stack<Coord>();
    const backwardStack = new Stack<Coord>();

    return genericBidirectionalSearch(forwardsStack, backwardStack, forwardsDistances, backwardsDistances, start, goal, weights, walls);
}

export function bidirectionalGBFS(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), heuristic: string) {
    const forwardsDistances = new HashMap<Coord, number>();
    const backwardsDistances = new HashMap<Coord, number>();
    const forwardsComparator = stringToHeuristic.get(heuristic)(goal);
    const backwardsComparator = stringToHeuristic.get(heuristic)(start);
    const forwardsQueue = new PriorityQueue<Coord>(forwardsComparator);
    const backwardQueue = new PriorityQueue<Coord>(backwardsComparator);

    return genericBidirectionalSearch(forwardsQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls);
}

export function bidirectionalDijkstra(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), heuristic: string) {
    const forwardsDistances = new HashMap<Coord, number>();
    const backwardsDistances = new HashMap<Coord, number>();
    const forwardsComparator = generateDijkstraComparator(forwardsDistances);
    const backwardsComparator = generateDijkstraComparator(backwardsDistances);
    const forwardsQueue = new PriorityQueue<Coord>(forwardsComparator);
    const backwardQueue = new PriorityQueue<Coord>(backwardsComparator);

    return genericBidirectionalSearch(forwardsQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls);
}

export function bidirectionalAStar(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), heuristic: string) {
    const forwardsDistances = new HashMap<Coord, number>();
    const backwardsDistances = new HashMap<Coord, number>();
    const forwardsComparator = generateAStarComparator(goal, forwardsDistances, heuristic);
    const backwardsComparator = generateAStarComparator(start, backwardsDistances, heuristic);
    const forwardsQueue = new PriorityQueue<Coord>(forwardsComparator);
    const backwardQueue = new PriorityQueue<Coord>(backwardsComparator);

    return genericBidirectionalSearch(forwardsQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls);
}

export function bidirectionalRandom(start: Coord, goal: Coord, walls: boolean()(), weights: number()(), heuristic: string) {
    const forwardsDistances = new HashMap<Coord, number>();
    const backwardsDistances = new HashMap<Coord, number>();
    const comparator = generateRandomComparator();
    const forwardsQueue = new PriorityQueue<Coord>(comparator);
    const backwardQueue = new PriorityQueue<Coord>(comparator);

    return genericBidirectionalSearch(forwardsQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls);
}

genericPathfinding.ts


// Generic pathfinding algo for searching from a source. Parameterized with the data structure used to make it generic
export function genericUnidirectionalSearch(
    start: Coord,
    goal: Coord,
    agenda: Collection<Coord>,
    distances: HashMap<Coord, number>,
    weights: number()(),
    walls: boolean()()) {

    const path = new HashMap<Coord, Coord>();
    const visited = initialseGridWith(false);
    const considered = initialseGridWith(false);
    const frames: GridFrame() = ();

    agenda.add(start);
    visited(start.row)(start.col) = true;
    distances.add(start, 0);

    while (!agenda.isEmpty()) {
        const isFound = considerNextNode(path, visited, agenda, goal, weights, considered, walls, distances, frames);

        if (isFound) {
            const finalPath = pathMapToGrid(path, goal);

            createFinalPathFrame(finalPath, visited, considered, frames);
            break;
        }
    }

    return frames;
}

// Generic pathfinding algo for searching from both the source and goal concurrently
export function genericBidirectionalSearch(
    forwardAgenda: Collection<Coord>,
    backwardAgenda: Collection<Coord>,
    forwardDistances: HashMap<Coord, number>,
    backwardDistances: HashMap<Coord, number>,
    start: Coord,
    goal: Coord,
    weights: number()(),
    walls: boolean()()) {

    const forwardPath = new HashMap<Coord, Coord>();
    const backwardPath = new HashMap<Coord, Coord>();

    const forwardVisited = initialseGridWith(false);
    const backwardVisited = initialseGridWith(false);

    const forwardConsidered = initialseGridWith(false);
    const backwardConsidered = initialseGridWith(false);

    const frames: GridFrame() = ();

    forwardDistances.add(start, 0);
    backwardDistances.add(goal, 0);

    forwardAgenda.add(start);
    backwardAgenda.add(goal);

    forwardVisited(start.row)(start.col) = true;
    backwardVisited(goal.row)(goal.col) = true;

    while (!forwardAgenda.isEmpty() && !backwardAgenda.isEmpty()) {
        const foundForwards = considerNextNode(forwardPath, forwardVisited, forwardAgenda, goal, weights, forwardConsidered, walls, forwardDistances, frames);
        const foundBackwards = considerNextNode(backwardPath, backwardVisited, backwardAgenda, start, weights, backwardConsidered, walls, backwardDistances, frames);

        mergeFrames(frames);

        if (foundForwards) {
            const finalPath = pathMapToGrid(forwardPath, goal);
            const mergedVisited = mergeGrids(forwardVisited, backwardVisited);
            const mergedConsidered = mergeGrids(forwardConsidered, backwardConsidered);

            createFinalPathFrame(finalPath, mergedVisited, mergedConsidered, frames);
            break;
        } else if (foundBackwards) {
            const finalPath = pathMapToGrid(backwardPath, start);
            const mergedVisited = mergeGrids(forwardVisited, backwardVisited);
            const mergedConsidered = mergeGrids(forwardConsidered, backwardConsidered);

            createFinalPathFrame(finalPath, mergedVisited, mergedConsidered, frames);
            break;
        } else if (hasIntersection(forwardConsidered, backwardConsidered)) {
            const intersection = getIntersection(forwardConsidered, backwardConsidered);
            const finalPath = mergeGrids(pathMapToGrid(forwardPath, intersection), pathMapToGrid(backwardPath, intersection));
            const mergedVisited = mergeGrids(forwardVisited, backwardVisited);
            const mergedConsidered = mergeGrids(forwardConsidered, backwardConsidered);

            createFinalPathFrame(finalPath, mergedVisited, mergedConsidered, frames);
            break;
        }
    }

    return frames;
}

// Generic function for making one step in a pathfinding algorithm
function considerNextNode(
    path: HashMap<Coord, Coord>,
    visited: boolean()(),
    agenda: Collection<Coord>,
    goal: Coord,
    weights: number()(),
    considered: boolean()(),
    walls: boolean()(),
    distances: HashMap<Coord, number>,
    frames: GridFrame()) {

    const currentPos = agenda.remove();
    const currentNeighbours = generateNeighbours(currentPos);

    considered(currentPos.row)(currentPos.col) = true;
    frames.push(generateGridFrame(visited, considered, ()));

    if (isSameCoord(currentPos, goal)) {
        return true;
    }

    currentNeighbours.forEach(neighbour => {
        if (!isOutOfBounds(neighbour) && !walls(neighbour.row)(neighbour.col)) {
            const neighbourDistance = distances.get(currentPos) + weights(neighbour.row)(neighbour.col);

            if (!visited(neighbour.row)(neighbour.col)) {
                distances.add(neighbour, neighbourDistance);
                agenda.add(neighbour);
                visited(neighbour.row)(neighbour.col) = true;
                path.add(neighbour, currentPos);
            }
        }
    });

    return false;
}

// Given two boolean grids, for all tiles, take the logical OR and return a new grid
function mergeGrids(grid: boolean()(), matrix: boolean()()) {
    const mergedGrid = initialseGridWith(false);

    for (let row = 0; row < HEIGHT; row++) {
        for (let col = 0; col < WIDTH; col++) {
            mergedGrid(row)(col) = grid(row)(col) || matrix(row)(col);
        }
    }

    return mergedGrid;
}

// Merge two animation frames to produce a frame that contains the information encoded in both
function mergeFrames(frames: GridFrame()) {
    const backwardsFrame = frames.pop();
    const forwardsFrame = frames.pop();
    const mergedFrame = initialseGridWith(TileFrame.Blank);

    for (let row = 0; row < HEIGHT; row++) {
        for (let col = 0; col < WIDTH; col++) {
            if (forwardsFrame(row)(col) === TileFrame.Searching || backwardsFrame(row)(col) === TileFrame.Searching) {
                mergedFrame(row)(col) = TileFrame.Searching;
            } else if (forwardsFrame(row)(col) === TileFrame.Frontier || backwardsFrame(row)(col) === TileFrame.Frontier) {
                mergedFrame(row)(col) = TileFrame.Frontier;
            }
        }
    }

    frames.push(mergedFrame);
}

// Add a frame containing the final path to the list
function createFinalPathFrame(path: boolean()(), visited: boolean()(), considered: boolean()(), frames: GridFrame()) {
    frames.push(generateGridFrame(visited, considered, path));
}

// Convert the hashmap pointer based path to a boolean grid based path
function pathMapToGrid(pathMap: HashMap<Coord, Coord>, goal: Coord) {
    const path = initialseGridWith(false);
    let pos = goal;

    while (pathMap.get(pos) !== undefined) {
        path(pos.row)(pos.col) = true;

        pos = pathMap.get(pos);
    }

    return path;
}

// Encode the state of a pathfinding algorithm into a frame 
function generateGridFrame(visited: boolean()(), considered: boolean()(), path: boolean()()) {
    const grid = initialseGridWith(TileFrame.Blank);

    for (let row = 0; row < HEIGHT; row++) {
        for (let col = 0; col < WIDTH; col++) {
            if (path.length > 0 && path(row)(col)) {
                grid(row)(col) = TileFrame.Path;
            } else if (considered(row)(col)) {
                grid(row)(col) = TileFrame.Searching;
            } else if (visited(row)(col)) {
                grid(row)(col) = TileFrame.Frontier;
            }
        }
    }

    return grid;
}

Comparators.ts


type Heuristic = (goal: Coord) => (c1: Coord, c2: Coord) => number;

// Map a heuristics JSX representation onto its implementation 
export const stringToHeuristic = new Map<string, Heuristic>((
    ("manhattan", generateManhattanComparator),
    ("euclidean", generateEuclideanComparator),
    ("chebyshev", generateChebyshevComparator)
));

// Return a comparator that compares by adding the distance from the starting tile and estimated distance from the goal
export function generateAStarComparator(goal: Coord, distances: HashMap<Coord, number>, heuristic: string) {
    return (c1: Coord, c2: Coord) => {
        const heuristicGenerator = stringToHeuristic.get(heuristic);
        const dijkstraComparison = generateDijkstraComparator(distances)(c1, c2);
        const heuristicComparison = heuristicGenerator(goal)(c1, c2);

        return dijkstraComparison + heuristicComparison;
    }
}

// Returns a comparator that compares using the distance from the starting tile
export function generateDijkstraComparator(distances: HashMap<Coord, number>) {
    return (c1: Coord, c2: Coord) =>
        distances.get(c2) - distances.get(c1);
}

// Returns a comparator that selects an item randomly
export function generateRandomComparator() {
    return (c1: Coord, c2: Coord) => Math.random() - 0.6;
}

// Given two coordinates (p1, p2) and (g1, g2), return comparator that compares using formula max(abs(p1 - g1), abs(p2 - g2))
function generateChebyshevComparator({ row: goalRow, col: goalCol }: Coord) {
    return ({ row: r1, col: c1 }: Coord, { row: r2, col: c2 }: Coord) =>
        Math.max(Math.abs(r2 - goalRow), Math.abs(c2 - goalCol)) - Math.max(Math.abs(r1 - goalRow), Math.abs(c1 - goalCol));

}

// Given two coordinates (p1, p2) and (g1, g2), return comparator that compares using formula sqrt((p1 - g1)^2 + abs(p2 - g2)^2)
function generateEuclideanComparator({ row: goalRow, col: goalCol }: Coord) {
    return ({ row: r1, col: c1 }: Coord, { row: r2, col: c2 }: Coord) => {
        const r1Dist = Math.sqrt(Math.pow(r1 - goalRow, 2) + Math.pow(c1 - goalCol, 2));
        const r2Dist = Math.sqrt(Math.pow(r2 - goalRow, 2) + Math.pow(c2 - goalCol, 2));

        return r2Dist - r1Dist;
    }
}

// Given two coordinates (p1, p2) and (g1, g2), return comparator that compares using formula abs(p1 - g1) + abs(p2 - g2) 
function generateManhattanComparator({ row: goalRow, col: goalCol }: Coord) {
    return ({ row: r1, col: c1 }: Coord, { row: r2, col: c2 }: Coord) =>
        (Math.abs(r2 - goalRow) + Math.abs(c2 - goalCol)) - (Math.abs(r1 - goalRow) + Math.abs(c1 - goalCol));

}

Is this a good conversion to typescript? Why this error?

I have this code to resize textarea elements when I need to:

function resize({ target }) {
  target.style.height = '1px'
  target.style.height = +target.scrollHeight + 'px'
}

export function textareaResize(el) {
  resize({ target: el })
  el.style.overflow = 'hidden'
  el.addEventListener('input', resize)
  return {
    destroy: () => el.removeEventListener('input', resize)
  }
}

I’m trying to convert this code to Typescript as:

function resizeTextArea(event: Event) {
  const target = event.target as HTMLTextAreaElement
  target.style.height = '1px'
  target.style.height = `${+target.scrollHeight}px`
}

export function textareaResize(element: HTMLTextAreaElement): { destroy: () => void} {
  resizeTextArea({ target: element })
  element.style.overflow = 'hidden'
  element.addEventListener('input', resizeTextArea)
  return {
    destroy: () => element.removeEventListener('input', resizeTextArea)
  }
}

but I have this error on line resizeTextArea({ target: element }) obviously:

Argument of type '{ target: HTMLTextAreaElement; }' is not assignable to parameter of type 'Event'.
  Type '{ target: HTMLTextAreaElement; }' is missing the following properties from type 'Event': bubbles, cancelBubble, cancelable, composed, and 17 more.ts(2345)

How can I fix it?

Maybe I’m wrong to use change it to this: function resizeTextArea(event: Event), right?