简体   繁体   English

使用查找数组方法的打字稿转译错误

[英]typescript transpiling error with find array method

I have this code in Typescript我在打字稿中有这段代码

/**
 * Team information
 */
export class Team {    
    constructor( public name: string ) {}
}

/**
 * Half side of each match, with team and score of the team
 */
export class SideMatch {
    constructor( public team: Team, public score: number) {}
}

/**
 * Two side matches, that represents the match itself
 */
export class Match {
    constructor( private game: SideMatch[] ) { }

    addScore(team: number, goal: number) {
        this.game[team].score += goal;
    }

    winner() : number {
        if( this.game[0].score > this.game[1].score )
            return 0;
        if( this.game[0].score < this.game[1].score )
            return 1;            
        return -1;            
    }

    getGame() {
        return this.game;
    }

    toString() {
        console.log( `${this.game[0].team.name} ${this.game[0].score} vs ${this.game[1].score} ${this.game[1].team.name}` );        
    }
}

/**
 * Team stats, with points, (todo: victories, draws, loses, goals forward, goals against, goals difference)
 */
export class TeamStats {

    constructor(public team: Team, public point: number) {}
}

export class Tournament {
    private teams: Team[] = [];
    private table: TeamStats[] = [];
    private fixtures: Match[] = [];

    constructor() {}

    public addTeam(teamName: string) {
        let team: Team = new Team(teamName);
        this.teams.push(team);
        console.log(this.teams);
        
        let teamStats = new TeamStats(team, 0);
        this.table.push(teamStats);
    }

    /**
     * Get the team
     * #question how to return only the Team type? It's requiring to define undefined
     * @param teamName 
     * @returns 
     */
    public getTeam(teamName :string) : Team {
        try {
            //let teamFound = new Team('temp');
            const teamFound = this.teams.find(t => t.name = teamName);
            console.log(`team found ${teamFound.name}`);
            
            if (teamFound === undefined) {
                throw new TypeError('The value was promised to always be there!');
              }
            return teamFound;   
        } catch (error) {
            throw error;
        }
            
    }

    public addMatch(team1: Team, team2: Team) {
        let sideMatch1: SideMatch = new SideMatch(team1, 0);
        let sideMatch2: SideMatch = new SideMatch(team2, 0);
        console.log(`add match - sm1 ${sideMatch1.team.name}` );
        console.log(`add match - sm2 ${sideMatch2.team.name}` );
        var game1: SideMatch[] = [];

        game1.push(sideMatch1);
        game1.push(sideMatch2);
        console.log(game1);
        
        let match1 = new Match( game1 );

        this.fixtures.push(match1);
    }

    public addMatchResults(matchIndex: number, score1: number, score2: number) {
        this.fixtures[matchIndex].addScore(0, score1);
        this.fixtures[matchIndex].addScore(1, score2);
        this.calculateMatchPoints(matchIndex);
    }

    private calculateMatchPoints(matchIndex: number) {
        let results : number = this.fixtures[matchIndex].winner();
        console.log(results);
        
        if (results !== -1)
        {
            console.log(this.fixtures[matchIndex].getGame());             
        }       
        
    }

    public getMatch(index: number) : Match {
        return this.fixtures[index];
    }

}

When I try to transpile my code in the CLI with当我尝试在 CLI 中使用

tsc src/compile.ts

It shows this error:它显示此错误:

D:\src\myApps\worldcup>tsc src/console
src/console.ts:80:42 - error TS2550: Property 'find' does not exist on type 'Team[]'. Do you need to change your target library? Try changing the 'lib' compiler option
 to 'es2015' or later.

80             const teamFound = this.teams.find(t => t.name = teamName);
                                            ~~~~


Found 1 error in src/console.ts:80

So I included the tsconfig.json with these settings:所以我将 tsconfig.json 包含在这些设置中:

{
  "compileOnSave": false,
  "compilerOptions": {
    "strictNullChecks": false,
   "lib": [
      "es2020",
      "dom",
    ]
  },  
}

Now I have two issues:现在我有两个问题:

  1. I can't transpile just using tsc src/console.ts.我无法仅使用 tsc src/console.ts 进行转译。 I need to use tsc -b now.我现在需要使用 tsc -b。 Why?为什么?

  2. When I run my code using these, something weird happens when I use getTeam directly and when I assign the result of getTeam method to a variable:当我使用这些运行代码时,当我直接使用 getTeam 以及将 getTeam 方法的结果分配给变量时,会发生一些奇怪的事情:

let worldCup2022: Tournament = new Tournament();

worldCup2022.addTeam('Brazil');
worldCup2022.addTeam('Canada');
console.log('t1 name with getTeam ' + worldCup2022.getTeam('Canada').name); // shows correctly t1 name Canada
console.log('t2 name with getTeam ' + worldCup2022.getTeam('Brazil').name); // shows correctly t2 name Brazil
const team1 = worldCup2022.getTeam('Canada');  
const team2 = worldCup2022.getTeam('Brazil');
console.log('t1 name ' + team1.name); // shows incorrectly t1 name as Brazil (last one got)
console.log('t2 name ' + team2.name); // shows incorrectly t1 name as Brazil (last one got)

TSC Issue TSC 问题

Have you run tsc -init in your root folder?您是否在根文件夹中运行 tsc -init ? This will initialize a tsconfig file, and then you can just run这将初始化一个 tsconfig 文件,然后你可以运行

tsc TSC

and it will compile all in the root directory.它将在根目录中编译所有内容。 My project structure is as such:我的项目结构是这样的:

File Structure文件结构

Team Name Issue团队名称问题

The problem finding a team is you're checking for the same type with = in寻找团队的问题是您正在使用 = in 检查相同类型

const teamFound = this.teams.find((t) => (t.name = teamName));

When you're actually looking to compare the value:当你真正想要比较价值时:

const teamFound = this.teams.find((t) => (t.name === teamName));

= vs == vs === = 对 == 对 ===

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM