Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript变量可以是任意一种类型_Typescript_Factory Pattern - Fatal编程技术网

Typescript变量可以是任意一种类型

Typescript变量可以是任意一种类型,typescript,factory-pattern,Typescript,Factory Pattern,我有一个packageMessage工厂函数,需要它根据type参数的值返回两种类型中的一种:PackagedChannel或packagedbuildchannel 功能: function packageMessage(id: string, type: PackagedChannelType, name?: string, position?: number): PackagedChannel | PackagedGuildChannel { var packaged: Packa

我有一个
packageMessage
工厂函数,需要它根据
type
参数的值返回两种类型中的一种:
PackagedChannel
packagedbuildchannel

功能:

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;
}
类型:

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;
}
但是,该函数生成的
属性“name/position”在类型“PackagedChannel”上不存在
错误

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

或者更好的是,如果您想要更多的类型安全性,您可能会使其过载

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 };
}

(现在好多了)