Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : how to create a type from a javascript object

I want to create a type or an interface with typescript from a javascript object that I don't know how it's created.

for example I want to create a type Request to use it in my function so I can make sure I pass the right parameter to the function :

let req = require("somewhere"); // my javascript object

function myfunction(request : Request) {
// some code
}

myfunction(req);// ok
myfunction(20);// Error

how can I create the Request type
like image 832
El houcine bougarfaoui Avatar asked Dec 19 '22 10:12

El houcine bougarfaoui


1 Answers

You can use the typeof keyword.

function myfunction(request : typeof req) {
// some code
}

Though be careful, if req is any you won't receive the type checking you want.


That said, if you want to access the request interface defined in express I believe you can access it as follows

import express = require('express')
function myfunction(request : express.Request) {
// some code
}
like image 141
Paarth Avatar answered Jan 07 '23 21:01

Paarth