我使用 Vue 开发了简单的 Laravel 应用程序。
访问 prop 时,我无法摆脱 Typescript 错误 TS2571: Object is of type 'unknown'.
。
我有两个 Vue 单文件组件:
家长:
<script lang="ts">
import { defineComponent, provide } from '@vue/composition-api';
import { AppConfig, appConfigKey } from './app-config';
import ChildComponent from './ChildComponent.vue';
export default defineComponent({
components: {
ChildComponent
},
setup() {
const appConfig: AppConfig = {
alias: 'foo',
name: 'foo',
shortName: 'foo',
url: 'foo'
};
provide(appConfigKey, appConfig)
}
})
</script>
儿童:
<script lang="ts">
import { defineComponent, inject } from '@vue/composition-api';
import { AppConfig, appConfigKey } from './app-config';
export default defineComponent({
setup() {
const appConfig: AppConfig = inject(appConfigKey);
console.log(appConfig.shortName); // TS error here
}
})
</script>
在我的 app-config 文件中,我有:
import { InjectionKey } from '@vue/composition-api';
export interface AppConfig {
alias: string;
name: string;
shortName: string;
url: string;
}
export const appConfigKey: InjectionKey<AppConfig> = Symbol('appConfig');
我的 tsconfig 文件:
{
"compilerOptions": {
"target": "es2015",
"module": "esnext",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"strict": true,
"strictNullChecks": true,
"strictPropertyInitialization": true,
"noImplicitAny": false,
"noImplicitReturns": false,
"noImplicitThis": false,
"noUnusedLocals": true,
"importHelpers": true,
"skipLibCheck": true,
"allowUnusedLabels": false,
"sourceMap": true,
"esModuleInterop": true,
"allowJs": true,
"baseUrl": ".",
"paths": {
"@/*": ["resources/assets/js/*"]
},
"lib": ["esnext", "dom"]
}
}
ESLint 没有抱怨,但 webpack 不想编译代码。 拜托,你能帮我弄清楚吗?我不是经验丰富的 Typescript 开发人员。我曾经使用过 Vue Options API。
答案 0 :(得分:0)
我看到一个不同的错误(使用 TypeScript 4.1.5):
<块引用>Type 'AppConfig | undefined' is not assignable to type 'AppConfig'. ts(2322)
...指向这一行:
<块引用>const appConfig: AppConfig = inject(appConfigKey);
^^^^^^^^^
您不需要输入 appConfig
,因为它已经可以推断为 AppConfig | undefined
:
const appConfig = inject(appConfigKey);
因为 appConfig
可能是 undefined
,所以使用 optional chaining 来引用它的属性:
console.log(appConfig?.shortName);
?