gpt4 book ai didi

angular - 属性类型 'slidesPerView' 不兼容

转载 作者:行者123 更新时间:2023-12-05 02:15:32 24 4
gpt4 key购买 nike

考虑一个带有 NGX-Swiper-Wrapper 插件的 Angular 6 应用程序。
Swiper 插件在 SwiperComponent 模板文件中调用:

<swiper [config]="customConfig">
...
</swiper>

为了保持组件文件的可读性,swiper 配置取自服务:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
import { SwiperConfigInterface } from 'ngx-swiper-wrapper';
...
export class SwiperComponent implements OnInit {
customConfig: SwiperConfigInterface;

constructor(private dataService: DataService) { }

ngOnInit() {
this.customConfig = this.dataService.getCustomConfig();
}

}

这是服务:

import { Injectable } from '@angular/core';
...
export class DataService {

constructor() { }

getCustomConfig() {
return {
observer: true,
direction: 'vertical',
slidesPerView: 'auto',
freeMode: true,
...
};
}

// Lots of other configs here
...

}

错误来了:

error TS2322: Type '{ ... slidesPerView: string; ...' is not assignable to type 'SwiperConfigInterface'. Types of property 'slidesPerView' are incompatible. Type 'string' is not assignable to type 'number | "auto"'.

这个错误可以粗暴的省略,只是将customConfig变量的类型从SwiperConfigInterface改为any。但是有人知道解决这个问题的更好方法吗?

最佳答案

SwiperConfigInterfaceslidesPerView 属性需要一个 number 类型的值或一个 'auto' 类型的值:

slidesPerView?: number | 'auto',

根据错误消息,Typescript 将 'auto' 视为此对象中的 string 类型:

return {
observer: true,
direction: 'vertical',
slidesPerView: 'auto',
freeMode: true,
...
};

您可以强制编译器将其视为 'auto' 类型的值,方法是强制转换它:

slidesPerView: 'auto' as 'auto',

关于angular - 属性类型 'slidesPerView' 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com