请看下面的代码片段,最后一行演示了一个错误。我该如何举报?
interface Type1 {
optionalA?: {
rendered: string;
text?: string;
};
}
type MyType = Type1["optionalA"];
const x: MyType = { rendered: "on" };
const y: Omit<MyType, "text"> = { rendered: "on" };
const w: MyType & { text?: string } = { rendered: "on" };
// this line fail with error Object literal may only specify known properties, and rendered does not exist in type ...
// while it shouldn't, this seems to be a bug caused by the combination of referencing a type by an optional member("optionalA") of
// another type, Omit and & operator, the problem seems to be the resolved object type looses all its members
const z: Omit<MyType, "text"> & { text?: string } = { rendered: "on" };
使用上面的代码片段创建一个.ts,编译器给出错误:对象字面量可能只指定已知属性,并且'rendered'在类型'Omit<{ rendered: string; text?: string | undefined; } | undefined, "text">&{text?:string |中不存在'不存在不明确的; }'.
预期结果:没有给出错误。
您发现的不是打字稿错误。这是您类型的预期行为
MyType
。当您查看界面 Type1
时,您将属性 optionalA
定义为可选。这意味着 optionalA
可以是 undefined
类型或您定义的类型。所以同样的规则也适用于你的MyType
。
实用程序函数 Omit from Typescript 的行为如下。如果类型不能为 null 或未定义,则 Omit
会从类型中选取所有属性并忽略曾经指定的属性并创建新类型。
但对于这种情况,省略类型也可能为 null 或未定义,Omit
将返回一个空对象作为新类型定义。
interface Type1 {
optionalA?: {
rendered: string;
text?: string;
};
}
type MyType = Type1["optionalA"];
// MyType = { rendered: string; text?: string; } | undefined
// because optionalA is an optional property in Type1
type OmitMyType = Omit<MyType, "text"> // results in {}
const z: OmitMyType & { text?: string } = { rendered: "on" };
// {} & { text?: string } does not match with {rendered: string}
这里有两种让您的代码运行的解决方案:
interface Type1 {
optionalA: { // make optionalA required
rendered: string;
text?: string;
};
}
OR
type MyType = NonNullable<MyType["optionalA"]>
// NonNullable removes null and undefined from type