我正在将一些JS转换为TS,就像这样:
class User {
constructor({ name, age }) {
this.name = name
this.age = age
}
// … + methods
}
我希望TypeScript能够推断出User
上的属性,或者有一些方法可以避免重复构造函数选项对象形状和类形状的形状。然而,我试图让TypeScript从选项中推断出类的形状,但没有成功:
type UserOptions = {
name: string
age: number
}
class User {
constructor(options: UserOptions) {
this.name = options.name // Property 'name' does not exist on type 'User'.
this.age = options.age // Property 'age' does not exist on type 'User'.
// or Object.assign(this, options), neither works
}
}
const user = new User({ name: 'Alice', age: 42 })
console.log(user.name, user.age) // Property 'name' does not exist on type 'User'.
https://www.typescriptlang.org/play?ssl=1& ssc = 1, pln = 16, pc/C4TwDgpgBAqgzhATgeTMAlgewHZygXigG8AoKKbAQwFsIAuKOYRdbAczKkrfooFdqAIyQkAviRIBjADaU4eeEmKdJOJoj6TgmRAApMaLLgaKUhtQEpl5csAAW6OADoqtAlAMY1LmtAD0flAACogGSKBQAOSuEJFQACaYEHjYmMBQEAAejuk4UKCQUaaRTpy2Ds7c0ISeRpU8UAHBoZCIEZFVcYnJFGkZ2Uwe2Png0JHFpTaNgTpQyIIAVhBaTnJw6GzYuvaOADQe5rgW + 9 = 83 #代码gq6pzkao46anzwnoliumrpfaii7qexso苏格兰皇家银行+ 6 + BiRACC0nQkli + yqDAALAAmKCiCwSVS4TDSCBOaSYNi6N5IHy0fb4xCrHhWJohMJtEBRGJdJIpPpZHJDEaFcbvEpAA
我注意到,如果我使用对象工厂函数而不是class
,它能够正确地推断形状:
type UserOptions = {
name: string
age: number
}
function User(options: UserOptions) {
return Object.assign({}, options)
}
const user = User({ name: 'Alice', age: 42 })
console.log(user.name, user.age)
https://www.typescriptlang.org/play?代码/C4TwDgpgBAqgzhATgeTMAlgewHZygXigG8AoKKbAQwFsIAuKOYRdbAczKkrfooFdqAIyQkAviRIAzPtgDGGHLASIAYtgAUmNFlwN4SVAtwBKYp0QRgfRNijJBAKwjyAdJThx0bDUVEAaKC0jOGMxCVkcJig + ZQIlJDV1IgoaXgByAEEAG3RZCDSA7l4AFgAmKFFQkgjcTCyIFyzMNnUYpBcqWgC2xDceYyA
是否有办法告诉TypeScript从UserOptions
推断出class User
的属性,反之亦然?
我觉得我不需要手动复制每个属性定义从UserOptions
到User
.
类似这篇博文中的第一个例子:https://fettblog.eu/low-maintenance-types-typescript/
您还有其他解决方案:
interface User {
name: string
age: number
}
class User {
constructor(options: User) {
this.name = options.name
this.age = options.age
}
}
const user = new User({ name: 'Alice', age: 42 })
console.log(user.name, user.age) // Property 'name' does not exist on type 'User'.