0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.