打字稿变量可以是任何一种类型

Typescript variable can be either type

我有一个 packageMessage 工厂函数,我需要它 return 两种类型之一:PackagedChannelPackagedGuildChannel 基于 type 参数.

函数:

function packageMessage(id: string, type: PackagedChannelType, name?: string, position?: number): PackagedChannel | PackagedGuildChannel {
    var packaged: PackagedChannel | PackagedGuildChannel;
    packaged.id = id;
    packaged.type = type;
    if (type === 'text') {
        packaged.name = name;
        packaged.position = position;
    }
    return packaged;
}

类型:

type PackagedChannelType = 'dm' | 'text' | 'unknown';
interface PackagedChannel {
    id: string;
    type: PackagedChannelType;
}
interface PackagedGuildChannel extends PackagedChannel {
    name: string;
    position: number;
}

但是,该函数会产生 Property 'name/position' does not exist on type 'PackagedChannel' 错误。

我该怎么做?非常感谢您的帮助:)

function packageMessage(id: string, type: PackagedChannelType, name?: string, position?: number): PackagedChannel | PackagedGuildChannel {
    return type === 'text' ? { id, type, name, position } : { id, type};
}

或者更好,如果你想要更多的类型安全,你可以重载它。

function packageMessage(id: string, type: 'text', name: string, position: number): PackagedGuildChannel

function packageMessage(id: string, type: 'dm' | 'unknown'): PackagedChannel

function packageMessage(id: string, type: PackagedChannelType, name?: string, position?: number): PackagedChannel | PackagedGuildChannel

function packageMessage(id: string, type: PackagedChannelType, name?: string, position?: number): PackagedChannel | PackagedGuildChannel {
    return type === 'text' ? { id, type, name, position } : { id, type };
}