Ser*_*yar 3 typescript angular angular6 swiper.js
考虑一个带有 NGX-Swiper-Wrapper 插件的 Angular 6 应用程序。
Swiper 插件在 SwiperComponent 模板文件中调用:
<swiper [config]="customConfig">
...
</swiper>
Run Code Online (Sandbox Code Playgroud)
为了保持组件文件的可读性,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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是服务:
import { Injectable } from '@angular/core';
...
export class DataService {
constructor() { }
getCustomConfig() {
return {
observer: true,
direction: 'vertical',
slidesPerView: 'auto',
freeMode: true,
...
};
}
// Lots of other configs here
...
}
Run Code Online (Sandbox Code Playgroud)
错误来了:
错误 TS2322: 类型 '{...slidesPerView: string; ...”不可分配给类型“SwiperConfigInterface”。属性“slidesPerView”的类型不兼容。类型“string”不可分配给类型“number |” “汽车”'。
这个错误可以通过残酷的方式省略,只需将customConfig变量的类型从更改SwiperConfigInterface为any。但有人知道解决这个问题的更好方法吗?
slidesPerView的属性需要SwiperConfigInterfacetype 的值number或 type 的值'auto':
slidesPerView?: number | 'auto',
Run Code Online (Sandbox Code Playgroud)
根据错误消息,Typescript 认为该对象的'auto'类型为:string
return {
observer: true,
direction: 'vertical',
slidesPerView: 'auto',
freeMode: true,
...
};
Run Code Online (Sandbox Code Playgroud)
您可以通过强制编译器将其视为类型值'auto':
slidesPerView: 'auto' as 'auto',
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1881 次 |
| 最近记录: |