最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Typescript : how to create a type from a javascript object - Stack Overflow

programmeradmin4浏览0评论

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

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
Share Improve this question asked Jan 14, 2017 at 23:54 El houcine bougarfaouiEl houcine bougarfaoui 37.3k10 gold badges39 silver badges38 bronze badges 3
  • You need to know in advance how the "javascript object" looks like, otherwise you can not create a type for it – Nitzan Tomer Commented Jan 14, 2017 at 23:55
  • @NitzanTomer my read of the question is how to make the parameter type and the required type covary – Paarth Commented Jan 14, 2017 at 23:58
  • its an object that is created using the function constructor http.IncomingMessage (nodeJs) its has a lot of properties – El houcine bougarfaoui Commented Jan 15, 2017 at 0:02
Add a comment  | 

1 Answer 1

Reset to default 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
}
发布评论

评论列表(0)

  1. 暂无评论