我有 Nuxt3-Wordpress REST API 项目(Typescript)。 我正在使用
"@woocommerce/woocommerce-rest-api": "^1.0.1", "@types/woocommerce__woocommerce-rest-api": "^1.0.5"
包列出来自 Wordpress 站点的 Nuxt 组件中的所有产品。
因此,我创建了一个具有以下内容的可组合项:
/**
* WordPress Composables
* A collection of WordPress composable functions.
*/
import WooCommerceRestApi from '@woocommerce/woocommerce-rest-api';
import { type Product } from '@/types/woocommerce';
const useWooCommerceApi = () => {
const config = useRuntimeConfig();
const WP_URL: string = config.WP_URL;
const WP_CONSUMER_KEY: string = config.WP_CONSUMER_KEY;
const WP_CONSUMER_SECRET: string = config.WP_CONSUMER_SECRET;
const api = new WooCommerceRestApi({
url: WP_URL || '',
consumerKey: WP_CONSUMER_KEY || '',
consumerSecret: WP_CONSUMER_SECRET || '',
version: 'wc/v3',
});
const listProducts = async (): Promise<Product[]> => {
const response = await api.get('products', {
per_page: 20,
});
return response.data as Product[];
};
return {
listProducts,
};
};
export default useWooCommerceApi;
但是,我收到 WP_URL、WP_CONSUMER_KEY、WP_CONSUMER_SECRET 错误:类型“未知”无法分配给类型“字符串”。
在我的 nuxt-config-ts 中:
runtimeConfig: {
public: {
WP_URI: process.env.WP_URI,
WP_CONSUMER_KEY: process.env.WP_CONSUMER_KEY,
WP_CONSUMER_SECRET: process.env.WP_CONSUMER_SECRET,
},
},
这是什么原因造成的,我该如何解决这个问题?
我通过使用解决了这个问题:
const WP_URL: string = (config.WP_URL as string) || '';
const WP_CONSUMER_KEY: string = (config.WP_CONSUMER_KEY as string) || '';
const WP_CONSUMER_SECRET: string = (config.WP_CONSUMER_SECRET as string) || '';