假设定义了以下类型:
interface Shape {
color: string;
}
Run Code Online (Sandbox Code Playgroud)
现在,请考虑以下方法为此类型添加其他属性:
延期
interface Square extends Shape {
sideLength: number;
}
Run Code Online (Sandbox Code Playgroud)
路口
type Square = Shape & {
sideLength: number;
}
Run Code Online (Sandbox Code Playgroud)
两种方法有什么区别?
而且,为了完整性和出于好奇,有没有其他方法可以产生可比较的结果?
每当我必须使用具有组合联合类型的对象时,打字稿都会抱怨我尝试访问的属性,并且我也没有获得自动完成功能。例如这个:
interface A {
id: string;
value: number;
}
interface B {
result: string;
}
export type Types = A | B;
function test(obj: Types) {
obj.result; // want to work with obj as though it implements interface B
}
Run Code Online (Sandbox Code Playgroud)
当我从打字稿访问result、id、 时,出现错误:value
Property 'result' does not exist on type 'Types'.
Property 'result' does not exist on type 'A'
Run Code Online (Sandbox Code Playgroud)
有什么方法可以缩小接口类型,以便获得更好的 IDE 体验吗?
我有一个带有以下签名的对象属性。
handleItem = (data: Output & { isValid: boolean }) => {}
Run Code Online (Sandbox Code Playgroud)
我不明白的&部分。
基本上我试图将一些参数传递为:
handleItem (outputItem, { isValid: false })
Run Code Online (Sandbox Code Playgroud)
我收到一个错误
Expected 1 arguments, but got 2.'
如何传递 values 属性?&在这种情况下如何使用?