【问题标题】:Argument of type 'string | undefined' is not assignable to parameter of type 'string'. How can I solve the problem?\'string | 类型的参数undefined\' 不能分配给 \'string\' 类型的参数。我该如何解决这个问题?
【发布时间】:2022-08-13 21:13:01
【问题描述】:

我想通过id删除一个元素,但是TS编译器发誓undefined type可以来。我不知道该怎么办了。我只是在学习:(

\'string | 类型的参数undefined\' 不能分配给 \'string\' 类型的参数。 类型 \'undefined\' 不能分配给类型 \'string\'。

项目页面

const removeProject = (id: string) => {
    projectServer.deleteProject(id);
    return (
        <div className=\"projectPage\">
            {projects.map(projects =>
                <ProjectItem project={projects} key={projects.id} removeProject={removeProject} />
            )}
        </div>
    );
}

项目项目

interface IProjectProps {
    project: Project,
    removeProject: (id: string) => void 
}

export const ProjectItem: FC<IProjectProps> = ({project, removeProject}) => {
    return (
        <div className=\"projectItem\">
            <div className=\"name\">{project.id}</div>
            <div className=\"name\">{project.name}</div>
            <div className=\"description\">{project.description}</div>
            <div className=\"actionBar\">
                <Button onClick={() = removeProject(project.id)} text=\"Delete\"/>
            </div>
        </div>
    );
}

类项目

export class Project {
    id: string;
    name: string;
    description: string;
    constructor() {
        this.id = \'\';
        this.name = \'\';
        this.description = \'\';
    }
}
  • 你可以写字符串 |未定义,而不仅仅是字符串

标签: reactjs typescript


【解决方案1】:
export class Project {
id?: string;
name?: string;
description?: string;
...

文档链接 - https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 2021-04-20
    • 2021-10-02
    • 2021-10-18
    • 2019-09-23
    • 2021-10-06
    • 2020-04-15
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多