相关疑难解决方法(0)

打字稿界面 - 可以使"一个或另一个"属性成为必需吗?

可能是一个奇怪的问题,但我很好奇是否可以创建一个需要一个属性或另一个属性的接口.

所以,例如......

interface Message {
    text: string;
    attachment: Attachment;
    timestamp?: number;
    // ...etc
}

interface Attachment {...}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我想确定是存在text还是attachment存在.

希望这是有道理的.

提前致谢!


编辑:这就是我现在正在做的事情.认为它有点冗长(输入botkit for slack).

interface Message {
    type?: string;
    channel?: string;
    user?: string;
    text?: string;
    attachments?: Slack.Attachment[];
    ts?: string;
    team?: string;
    event?: string;
    match?: [string, {index: number}, {input: string}];
}

interface AttachmentMessageNoContext extends Message {
    channel: string;
    attachments: Slack.Attachment[];
}

interface TextMessageNoContext extends Message {
    channel: string;
    text: string;
}
Run Code Online (Sandbox Code Playgroud)

typescript

34
推荐指数
9
解决办法
2万
查看次数

为什么 A | B 允许两者结合,我该如何预防?

我很惊讶地发现 TypeScript 不会抱怨我做这样的事情:

type sth = { value: number, data: string } | { value: number, note: string };
const a: sth = { value: 7, data: 'test' };
const b: sth = { value: 7, note: 'hello' };
const c: sth = { value: 7, data: 'test', note: 'hello' };
Run Code Online (Sandbox Code Playgroud)

我想也许value被选为类型联合判别式或其他东西,因为我唯一能想出解释这一点的是,TypeScript 是否以某种方式number在这里理解1 | 2为例如的超集。

所以我改变valuevalue2在第二对象上:

type sth = { value: number, data: string } | { value2: number, note: …
Run Code Online (Sandbox Code Playgroud)

xor typescript typescript-types

16
推荐指数
2
解决办法
1431
查看次数

Typescript是否支持互斥类型?

我有一个带参数的方法.我希望Typescript验证传入的对象(在typescript编译时,我理解运行时是一个不同的动物)只满足一个允许的接口.

例:

interface Person {ethnicity: string;}
interface Pet {breed: string;}
function getOrigin(value: Person ^ Pet){...}

getOrigin({}); //Error
getOrigin({ethnicity: 'abc'}); //OK
getOrigin({breed: 'def'}); //OK
getOrigin({ethnicity: 'abc', breed: 'def'});//Error
Run Code Online (Sandbox Code Playgroud)

我意识到这Person ^ Pet不是有效的Typescript,但这是我认为首先尝试并且看似合理的东西.

typescript

13
推荐指数
2
解决办法
2331
查看次数

标签 统计

typescript ×3

typescript-types ×1

xor ×1