Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript-属性a和b如何同时存在或不存在_Typescript_Properties - Fatal编程技术网

Typescript-属性a和b如何同时存在或不存在

Typescript-属性a和b如何同时存在或不存在,typescript,properties,Typescript,Properties,在param obj中,它可以有属性“a”、“b”和“c”,如{a:1、b:2、c:3},如何使用typescript定义传递“a”是否也需要传递“b”,如果不传递“a”也不传递参数中的“b” 任何人都可以为我回答这个问题,谢谢这是最好的建模方法,使用a和b创建一个新接口,并将其作为原始对象中的可选参数: function test(obj) { } 现在,这是有效的ts: interface Foo { a: number, b: number } interface Bar {

在param obj中,它可以有属性“a”、“b”和“c”,如
{a:1、b:2、c:3}
,如何使用typescript定义传递“a”是否也需要传递“b”,如果不传递“a”也不传递参数中的“b”


任何人都可以为我回答这个问题,谢谢

这是最好的建模方法,使用
a
b
创建一个新接口,并将其作为原始对象中的可选参数:

function test(obj) {

}
现在,这是有效的ts:


interface Foo {  a: number, b: number }

interface Bar {
  foo?: Foo
  c: number
}
但这会引发透明错误:

bar1: Bar = { c: 3 };
bar2: Bar = { foo: { a: 1, b: 2 }, c: 3};
从语义上讲,这更有意义,因为您所说的是两个属性被约束在一起

// INVALID TS >>>
bar1: Bar = { foo: { a: 1 }, c: 3}
bar2: Bar = { foo: { b: 2 }, c: 3}
注意:您可能需要在tsconfig.json文件中添加enable
“strictNullChecks”:true、

如果无法启用strictNullChecks,则可以使用此选项

const foo = (obj: { c: number } | {  a: number, b: number, c: number }) => {};
后面的语句说明
a
b
都必须是数字,或者
a
b
都必须是
null/undefined

const foo = (obj: { c: number, a?: null, b?: null} | {  a: number, b: number, c: number }) => {};
function test(obj: { a: number, b: number, c: number } | { a?: never, b?: never, c: number }) {}

test({ a: 1, b: 2, c: 3 });
test({ c: 1 });