Problems when importing a module in TypeScript 4

I'm learning TypeScript, my development environment is:

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:

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

let alice: auth.User
alice = {
  email: '[email protected]',
  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?

Upvotes: 0

Views: 501

Answers (1)

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: '[email protected]',
  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.

Upvotes: 0

Related Questions