Last active
November 14, 2022 14:26
-
-
Save alxpsr/8846d702ff2f66535bcbf8ee8d173f67 to your computer and use it in GitHub Desktop.
Infer Real Case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//== 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