I have these types
type Asset = {
id: string,
name: string,
recordedBy: string
}
type User = {
id: string,
name: string,
dob?: Date
}
type Device = {
id: string,
name: string,
location: [number, number]
}
// etc...
I have a Class
type Name = 'asset' | 'user' | 'device' // etc.
type Convert<N extends Name> =
N extends 'asset' ? Asset
: N extends 'user' ? User
: N extends 'device' ? Device : N
class Read<N extends Name>
{
name: N;
constructor(name: N)
{
this.name = name;
}
get = async (): Promise<Convert<N>> =>
{
// code here
};
}
When I use the Class above
const read = new Read('user');
const user = await read.get();
The type of the variable user
is what I expect (User
).
But I have a function like this
const build = <N extends Name>(names: N[]): Read<N>[] =>
{
return names.map(name => new Read(name));
};
const [readAsset, readDevice] = build(['user', 'device']);
Types of readAsset
and readDevice
aren’t what I expect
const readAsset: Read<"asset" | "device">
const readDevice: Read<"asset" | "device">
So when I run get
in each ones.
const asset = await readAsset.get();
const device = await readDevice.get();
Types of those results are
const asset: Asset | Device
const device: Asset | Device
What should I do in order to change results to
const readAsset: Read<"asset">
const readDevice: Read<"device">
As well as
const asset: Asset
const device: Device
Without casting
I also expect we use the function build
. Thank everbody.
Xuân Minh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.