Skip to content

Instantly share code, notes, and snippets.

@alxpsr
Last active November 14, 2022 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alxpsr/8846d702ff2f66535bcbf8ee8d173f67 to your computer and use it in GitHub Desktop.
Save alxpsr/8846d702ff2f66535bcbf8ee8d173f67 to your computer and use it in GitHub Desktop.
Infer Real Case
//== Wrong way
export class User {
name: string;
age: number;
accessToken: string;
constructor(options: {
age: number;
name: string;
accessToken?: string;
}) {
this.age = options.age;
this.name = options.name;
this.accessToken = options.accessToken!;
}
}
class App {
currentUser!: User;
initialize(): void {
const options = {
age: 12,
name: 'ad',
acessToken: 'xsd3' // добавляем опечатку acessToken вместо accessToken
}
this.currentUser = new User(options); // Тут не будет ошибки, компилятор не поймет что есть опечатка
}
}
//========= Right way
// Создаем тип: если наш дженерик С имеет конструктор с аргументом, то берем тип аргумента
type UserConstructorOptions<C> = C extends { new(arg: infer A): any } ? A : never;
export class User {
name: string;
age: number;
accessToken: string;
constructor(options: {
age: number;
name: string;
accessToken?: string;
}) {
this.age = options.age;
this.name = options.name;
this.accessToken = options.accessToken!;
}
}
class App {
currentUser!: User;
initialize(): void {
const options: UserConstructorOptions<typeof User> = {
age: 12,
name: 'ad',
acessToken: 'xsd3' // тут уже компилятор нам подчеркнет красным, укажет на ошибку
}
this.currentUser = new User(options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment