Problems when importing a module in TypeScript 4

Viewed 65

I'm learning TypeScript, my development environment is:

  • TS v4.7.4
  • deno 1.24.2 (release, x86_64-unknown-linux-gnu) as compiler
  • JavaScript language version used: ES2016
  • Editor: Visual Studio Code
  • plugins installed: JavaScript and TypeScript Nightly v4.9, TypeScript Importer v2.0.1, TypeScript Toolbox v0.5.0

I'm following an old tutorial (which uses TS 4.1.3 with node.js and ES5 for JS), and I have a certain questions with this exercise:

  • Create types/AuthTypes.d.ts with this content:
declare module 'AuthTypes' {
  export interface User {
    email: string
    roles: Array<string>
    source?: string
  }
}
  • Create user.ts with this initial content:
///<reference path = './types/AuthTypes.d.ts'/>
import auth = require('AuthTypes')

let alice: auth.User
alice = {
  email: 'alice@snow.com',
  roles: ['super_admin'],
  source: 'facebook',
  amigo: 'chesu'
}

console.log(alice);

I'm getting three error messages from linter:

  1. Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead.
  2. Relative import path "AuthTypes" not prefixed with / or ./ or ../
  3. Type '{ email: string; roles: string[]; source: string; amigo: string; }' is not assignable to type 'User'. Object literal may only specify known properties, and 'amigo' does not exist in type 'User'.

The third error is expected. So I changed

///<reference path = './types/AuthTypes.d.ts'/>
import auth = require('AuthTypes')

with this line:

import * as auth from './types/AuthTypes.d.ts'

The program is running now with no errors when it should not because the nonexisting property amigo. How should this problem be properly solved?

1 Answers

That problem was (almost) resolved thanks to this video.

My new content for types/AuthTypes.d.ts file is like this:

export interface User {
  email: string
  roles: Array<string>
  source?: string
}

and for user.ts is:

import * as auth from './types/AuthTypes.d.ts'

let alice: auth.User
alice = {
  email: 'alice@snow.com',
  roles: ['super_admin'],
  source: 'facebook',
  amigo: 'chesu'
}

console.log(alice);

With this change every exported classes and their properties are properly recognized, and I'm getting the expected error message on property amigo (on IDE) only.

Related