Typescript意外为null |未定义,而不是字符串| null
我有一个实现接口IFoo的类Foo,实例是IFoo的类型。构造函数参数以IFoo对象的形式出现。为此,我使用以下代码:Typescript意外为null |未定义,而不是字符串| null,typescript,Typescript,我有一个实现接口IFoo的类Foo,实例是IFoo的类型。构造函数参数以IFoo对象的形式出现。为此,我使用以下代码: 接口IFoo{ 名称:字符串; 年龄:人数; nullableProp:string | null; } 福班{ 名称:字符串; 年龄:人数; nullableProp:string | null; 建造师({ 名称='默认名称', 年龄=35岁, nullableProp=null, } = {}) { this.name=名称; 这个。年龄=年龄; this.nullabl
接口IFoo{
名称:字符串;
年龄:人数;
nullableProp:string | null;
}
福班{
名称:字符串;
年龄:人数;
nullableProp:string | null;
建造师({
名称='默认名称',
年龄=35岁,
nullableProp=null,
} = {}) {
this.name=名称;
这个。年龄=年龄;
this.nullableProp=nullableProp;
}
}
常量fooData:IFoo={
名字:“拉拉”,
年龄:42,,
nullableProp:“StringValue”
};
const foo=新foo(fooData)//这一行有错误
然后我收到了错误(如所附的屏幕截图)。
请帮助我了解那里发生了什么以及如何修复:)
UPD:可能的解决方案:
接口IFoo{
名称:字符串;
年龄:人数;
nullableProp:string | null;
}
福班{
名称:字符串;
年龄:人数;
nullableProp:string | null;
建造师({
名称='默认名称',
年龄=35岁,
nullableProp=null,
}:部分={}){
this.name=名称;
这个。年龄=年龄;
this.nullableProp=nullableProp;
}
}
常量fooData:IFoo={
名字:“拉拉”,
年龄:42,,
nullableProp:“StringValue”
};
const foo=新foo(fooData);
您的构造函数接受类型为{name?:string |未定义;age?:number |未定义;nullableProp?:null |未定义;}
的参数,但您为它提供了类型为IFoo
的参数。好的,我应该解释一下我期望从这个类中得到什么样的行为。创建的对象的类型必须是IFoo,而构造函数接受相同类型的对象,但如果没有其任何属性,则会将其替换为默认值(IFoo类型中为此属性指定的属性之一)。我找到了这个解决方案,它似乎有效。它有多正确?(原稿中UPD后面的代码)