我想从库声明中重写属性类型,我尝试使用接口重写,但我得到了错误Subsequent property declarations must have the same type
。我该如何解决这个问题?
// this is library declaration
declare class Auth {
user: Record<string, string | number> | null
// i want to remove null type in user property, because i dont want to use `non-null assertion` in line 21
// i cant change this file because it is 3rd party library
}
// ------------------------------
// our file
// my override interface, but fail
interface Auth {
user: Record<string, string | number>
}
const a: Auth = {
user: {
name: 'joko',
age: 30
}
}
const userName = a.user!.name
// const userName = a.user.name // <-- i want use like this, because i'm sure that this property is always available
我尝试使用接口重写库声明,但失败了。我期望的结果是,只需使用我们的代码,就可以在不触及或更改库的情况下重写类型。
我自己解决了。在我的情况下,我想覆盖nuxt-auth
模块上的Auth
接口。解决方案如下:
- 从node_modules中复制模块类型到我们的类型文件中。然后更改相应的接口(将
Auth
更改为IAuth
)。IAuth
是我们修改后的接口。
import { IAuth } from '~/interface/auth/model';
export * from '@nuxtjs/auth-next/dist';
declare module 'vue/types/vue' {
interface Vue {
$auth: IAuth;
}
}
// rest of the file
- 将上面的文件添加到
tsconfig.json
中作为paths
,这样typescript将使用该文件而不是原来的模块类型。
"compilerOptions": {
// ...
"paths": {
"@nuxtjs/auth-next": [
"types/nuxt-auth.d.ts"
],
// ...
}
// ...
}
瞧,使用修改后的接口
,类型按预期运行了。