我不太知道如何表达这个问题,但我偶然发现了一个特殊的问题。我试图Thingy通过使用foo类型为Kind.
interface AKind {
kind: 'A';
}
interface BKind {
kind: 'B';
}
interface CKind {
kind: 'C';
}
type Kind = AKind | BKind | CKind;
type ExCThingy = {
foo: Exclude<Kind, CKind>,
something: 'test';
}
type CThingy = {
foo: CKind,
somethingelse: 'test2';
}
type Foo = {
foo: Kind
}
function DoSomething(args: ExCThingy | CThingy) {
function isCThingy(args: ExCThingy | CThingy): args is CThingy {
return args.foo.kind === 'C';
}
if (isCThingy(args)) {
//Do C thing
return;
}
//else Do ExC thing
return;
}
const a: AKind = {
kind: 'A',
}
const b: BKind = {
kind: 'B',
}
const c: CKind = {
kind: 'C',
}
const fooArray: Foo[] = [{
foo: a,
},
{
foo: b,
},
{
foo: c,
}];
fooArray.map(e => DoSomething({
foo: e.foo,
something: 'test',
somethingelse: 'test2'
}));
ts 编译器抱怨:
Argument of type '{ foo: Kind; something: "test"; somethingelse: "test2"; }' is not assignable to parameter of type 'ExCThingy | CThingy'.
Type '{ foo: Kind; something: "test"; somethingelse: "test2"; }' is not assignable to type 'CThingy'.
Types of property 'foo' are incompatible.
Type 'Kind' is not assignable to type 'CKind'.
Type 'AKind' is not assignable to type 'CKind'.
Types of property 'kind' are incompatible.
Type '"A"' is not assignable to type '"C"'.(2345)
翻阅古今
相关分类