属性 'slidesPerView' 的类型不兼容
Types of property 'slidesPerView' are incompatible
考虑使用 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
。但是有人知道解决这个问题的更好方法吗?
SwiperConfigInterface
的 slidesPerView
属性 需要 number
类型的值或 'auto'
:
类型的值
slidesPerView?: number | 'auto',
根据错误消息,Typescript 将 'auto'
视为此对象中的 string
类型:
return {
observer: true,
direction: 'vertical',
slidesPerView: 'auto',
freeMode: true,
...
};
您可以强制编译器将其转换为 'auto'
类型的值:
slidesPerView: 'auto' as 'auto',
考虑使用 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
。但是有人知道解决这个问题的更好方法吗?
SwiperConfigInterface
的 slidesPerView
属性 需要 number
类型的值或 'auto'
:
slidesPerView?: number | 'auto',
根据错误消息,Typescript 将 'auto'
视为此对象中的 string
类型:
return {
observer: true,
direction: 'vertical',
slidesPerView: 'auto',
freeMode: true,
...
};
您可以强制编译器将其转换为 'auto'
类型的值:
slidesPerView: 'auto' as 'auto',