12

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 
3
  • You need to know in advance how the "javascript object" looks like, otherwise you can not create a type for itCommentedJan 14, 2017 at 23:55
  • @NitzanTomer my read of the question is how to make the parameter type and the required type covary
    – Paarth
    CommentedJan 14, 2017 at 23:58
  • its an object that is created using the function constructor http.IncomingMessage (nodeJs) its has a lot of propertiesCommentedJan 15, 2017 at 0:02

1 Answer 1

21

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 } 
4
  • thank you for your answer, but I want something visible without using typeofCommentedJan 15, 2017 at 0:05
  • 1
    In that case I feel your question is unclear. Are you asking what type to use for the interface that you imported? If that's what you'd want you'll need to tell us exactly what you're importing and exactly how you're using it.
    – Paarth
    CommentedJan 15, 2017 at 6:20
  • yes that's exactly what I want, what I import is the request object defined in the expressJS library, as I said it has a lot of propertiesCommentedJan 15, 2017 at 11:41
  • 1
    @BougarfaouiElhoucine I updated the answer, does that work for you?
    – Paarth
    CommentedJan 16, 2017 at 3:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.