user3794648
user3794648

Reputation: 483

Angular 12 : Using Custom types

I'm new to Angular12. I'm trying to create a simple custom type in my application to represent the logged in user. I have the following in types/user.d.ts:

export interface User {
    id: string,
    password: string,
    name: string
}

Then, I have the following service in src/app/login.service.ts

import { Injectable } from '@angular/core';


@Injectable({
  providedIn: 'root'
})
export class LoginService {
    constructor() { }

    authenticate(loginData:User) : User {
        //for now authenticate all attempts
        return loginData;
    } 
    
}

As per the tutorial I read, I've added the following to tsconfig.json:

  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true,
    "typeRoots": [
      "/types",
      "node_modules/@types"
    ]
  }
}
When I try to compile, I get the following error:

Error: src/app/login.service.ts:2:20 - error TS2307: Cannot find module '../types/User' or its corresponding type declarations.

How do I access custom types in Angular 12?

Upvotes: 0

Views: 1005

Answers (1)

Jeremy
Jeremy

Reputation: 1288

I think you are confusing an interface with a declarative type. To declare a type, you can change the verbiage in the types/user.d.ts to:

declare class User {
    id: string,
    password: string,
    name: string
}

Or, you could simply change the file to a standard .ts file, like user.interface.ts or better yet user.model.ts, and then import this interface at the top of your app component:

import { User } from '../user.model.ts

Upvotes: 1

Related Questions