Typescript接口:只需一个可选参数

jas*_*457 5 javascript typescript typescript-typings

我想定义一个接口,允许您提供contentOR,content_object但不能同时提供。您必须定义一个。在TypeScript中最简单的方法是什么?我知道我可以说content是string | object,但是如果我可以按照描述来定义内容,那么我的其余代码也会受益。

interface IModal {
    content?: string;
    content_object?: object;
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*ugh 9

type IModal = { content: string; content_object?: undefined } |
              { content_object: object; content?: undefined }
Run Code Online (Sandbox Code Playgroud)

这个答案只包含代码,因此根据自动化系统来说是不好的。