n83 n83 - 1 year ago 64
TypeScript Question

How can I import OS in Typescript?

I'm running VS Code Version 1.5.3 with TypeScript 2 and I can't get my 'os' import to work. I managed to resolve other dependencies, such as Express, by running

typings install express --save

But I can't find a typing for OS. Probably since it's not a third party library. But then how do I resolve the following import?

import { os } from 'os';

The message I get in VS Code is "Cannot find module 'os'"

Answer Source

You need to add a typings file. Ususally, you install typing files (ending in d.ts) from typings, which you install using npm install -g typings in the command line.

However, I can't seem to find a typing for os which is weird, so you can create a fake module definition to solve it in the meantime:

// file: os.d.ts
declare namespace os {
   interface OsStatic { ... everything os has ... }

declare var os: os.OsStatic;

declare module "os" {
    export = os;

What we do here can be separated into three parts:

  1. the namespace defines the interfaces that compose the library
  2. the var is the exported / main object of the library
  3. the module is an ambient module, since it's name is a string. Using that string, visual studio can locate the module and allow you to import

In general, you should read about typings to manage typing files, but this should work.