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 };
}
(现在好多了)