当遇到报错如:
不能将类型“{ children: Element; src: string; alt: string; height: "xSmall"; posititon: string; onClick: () => void; }”分配给类型“IntrinsicAttributes & LittleIconProps”。 类型“IntrinsicAttributes & LittleIconProps”上不存在属性“children”。ts(2322)
解决办法:
在报错组件interface加上:
children?: React.ReactNode;
针对有js基础学习ts的指南:www.typescriptlang.org/docs/handbo…
TIP: ts是强类型语言,所以容易出现以上错误
定义类型
您可以在 JavaScript 中使用各种设计模式。但是,某些设计模式很难自动推断类型(例如,使用动态编程的模式)。为了解决这些情况,TypeScript 支持 JavaScript 语言的扩展,它为您提供了告诉 TypeScript 类型应该是什么的地方。
例如,要创建一个包含name: string和的推断类型的对象id: number,您可以编写:
const user = {
name: "Hayes",
id: 0,
};
尝试
您可以使用声明明确描述该对象的形状interface:
interface User {
name: string;
id: number;
}
尝试
interface然后,你可以使用类似: TypeName变量声明后的语法来声明一个符合你的 new 形状的 JavaScript 对象:
const user: User = {
name: "Hayes",
id: 0,
};
尝试
如果你提供的对象与你提供的接口不匹配,TypeScript 会发出警告:
interface User {
name: string;
id: number;
}
const user: User = {
username: "Hayes",
Object literal may only specify known properties, and 'username' does not exist in type 'User'.Object literal may only specify known properties, and 'username' does not exist in type 'User'.
id: 0,
};
尝试
由于 JavaScript 支持类和面向对象编程,因此 TypeScript 也支持。你可以在类中使用接口声明:
interface User {
name: string;
id: number;
}
class UserAccount {
name: string;
id: number;
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
const user: User = new UserAccount("Murphy", 1);
尝试
您可以使用接口来注释函数的参数和返回值:
function deleteUser(user: User) {
// ...
}
function getAdminUser(): User {
//...
}
尝试
JavaScript中已经提供了一小部分基本类型:boolean、、、、、和,您可以在接口中使用它们。TypeScript 扩展了这个列表,添加了更多内容,例如bigint(允许任何内容)、 (确保使用此类型的人声明了类型是什么)、(不可能发生这种类型)和(返回值或没有返回值的函数)。null``number``string``symbol``undefined``anyunknownnevervoid``undefined
您将看到,构建类型有两种语法:接口和类型。您应该更喜欢。在需要特定功能时interface使用。type