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" ] } }
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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.