tst-reflect icon indicating copy to clipboard operation
tst-reflect copied to clipboard

There is no way to get Record type arguments

Open ciricc opened this issue 3 years ago • 2 comments

Hi. I've tried to get Record generic types, but nothing returned.

const t = getType<Record<string, boolean>>()
console.log(t.getTypeParameters(), t.getTypeArguments()) // [], []

ciricc avatar Jul 04 '22 17:07 ciricc

I'm sorry @ciricc, idk how but I missed this issue.


This is a little odd case. type is always resolved to its definition but in case of Record, its definition is an empty object allowing any property of given type (more specific any). I don't know how to handle it. I am able to handle it and force it to be type Record with given generic arguments (like Array) but there is a huge amount of similar types...

There is a workaround:

type Schema2 = {
	fields: {
		[prop: string]: SchemaFields
	}
}

const indexItemType = getType<Schema2>()
    .getProperties()
    .find(prop => prop.name == "fields").type
    .getProperties()
    .find(prop => prop.index).type;
console.log(indexItemType.name);

It's a special "__index" property.

Hookyns avatar Aug 02 '22 21:08 Hookyns

@Hookyns , ok, thank you for reply.

ciricc avatar Aug 04 '22 07:08 ciricc

@ciricc Test [email protected] and [email protected].

Records, Omit and other features creating type aliases should be supported. Combination of properties and indexes is generated. Indexes are no more part of properties and property.index was removed.

See type.getProperties(), type.getIndexes().

Hookyns avatar Aug 14 '22 12:08 Hookyns

@Hookyns Thank you. I will check it out

ciricc avatar Aug 14 '22 16:08 ciricc

Record Record<string, SchemaFields> will be generated as index [key: string]: SchemaFields, so:

type T = Record<string, SchemaFields>;
const t = getType<T>();
const index = t.getIndexes()[0];

console.log(index.keyType.name); // string
console.log(index.type.name); // SchemaFields

Hookyns avatar Aug 14 '22 17:08 Hookyns