2 回答
TA贡献1809条经验 获得超8个赞
您可以通过执行以下操作来传递任何对象,而无需 Typescript 抱怨:
export function filterVisualData(obj: any) {
const { data, playersOn, typesOn, resultsOn, toBeRemoved, teamsOn, xGOn, shotsOn } = obj
return data.filter(d => {
const result = d.success ? 'Successful' : 'Unsuccessful';
const players = playersOn.length === 0 || (playersOn.length > 0 && playersOn.includes(d.player_name));
const types = typesOn.length === 0 || (typesOn.length > 0 && typesOn.includes(capitalizeAllWords(d.type)));
const results = resultsOn.length === 0 || (resultsOn.length > 0 && resultsOn.includes(result));
const removed = !toBeRemoved.map(p => p.time).includes(d.time);
const shots = shotsOn.length === 0 || (shotsOn.length > 0 && shotsOn.includes(d.type));
const xG = xGOn.length === 0 || (xGOn.length > 0 && d.xG < Math.max(...xGOn));
const teams = teamsOn.length === 0 || (teamsOn.length > 0 && teamsOn.includes(d.team_name));
return players && types && results && removed && shots && xG && teams;
});
}
因此,在编译时不会出现错误,但在运行时仍然会出现错误。如果你没有通过playersOn,那么你就会崩溃Cannot read length of undefined。您需要为每个值实现故障保护。
TA贡献1719条经验 获得超6个赞
您还可以利用接口并将Partial其内置到 TypeScript 中。
export interface IData {
success: boolean;
player_name: string;
type: string;
time: string;
team_name: string;
}
export interface IBaseArgs {
data: IData[] ,
playersOn: <TypeHere>,
typesOn: <TypeHere>,
resultsOn: <TypeHere>,
toBeRemoved: <TypeHere>,
teamsOn: <TypeHere>,
xGOn: <TypeHere>,
shotsOn: <TypeHere>
}
export function filterVisualData<T extends Partial<IBaseArgs>>(obj: T) {
const {data, playersOn, typesOn, resultsOn, toBeRemoved, teamsOn, xGOn, shotsOn} = obj;
return data.filter(d => {
const result = d.success ? 'Successful' : 'Unsuccessful';
const players = playersOn.length === 0 || (playersOn.length > 0 && playersOn.includes(d.player_name));
const types = typesOn.length === 0 || (typesOn.length > 0 && typesOn.includes(capitalizeAllWords(d.type)));
const results = resultsOn.length === 0 || (resultsOn.length > 0 && resultsOn.includes(result));
const removed = !toBeRemoved.map(p => p.time).includes(d.time);
const shots = shotsOn.length === 0 || (shotsOn.length > 0 && shotsOn.includes(d.type));
const xG = xGOn.length === 0 || (xGOn.length > 0 && d.xG < Math.max(...xGOn));
const teams = teamsOn.length === 0 || (teamsOn.length > 0 && teamsOn.includes(d.team_name));
return players && types && results && removed && shots && xG && teams;
});
}
使用Partial将使所有键成为可选键,并且该函数将接受缺少一些键的对象。您还将获得 IntelliSense。
添加回答
举报