Motoko <>Typescript : Array

Hello community, I’m facing a misunderstanding with arrays from Motoko and Typescript.

Here is the problem:

// Motoko file
public type Entity = {
	tagList: ?[Text];
};
// Generated Typescript file
export interface Entity {
	'tagList': [] | [Array<string>]
};

And now the problems I’m facing in my Typescript frontend file :

/**
 *  IDE Error :
 *  Type 'string[]' is not assignable to type '[] | [string[]]'.
 */
public buildEntity(tagList: string[]): void {
	const entity: Entity = {
		tagList: tagList
	};
};
/**
 *  Not used, just to test
 *  IDE Error :
 *  Type '{ tagList: [string[]]; }' is missing the following properties from type 'Entity'
 */
public buildEntity(tagList: [string[]]): void {
	const entity: Entity = {
		tagList: tagList
	};
};
/**
 *  Runtime Error :
 *  Invalid opt record {tagList:opt vec text;} argument: [{"tagList":["tag1","tag2"]}]
 */
public buildEntity(tagList: []): void {
	const entity: Entity = {
		tagList: tagList
	};
};

Coming from Java, I am used to strong typing and I wonder if the problem does not come from there… Or maybe I missed something that is right in front of my eyes.

Could someone give me some help on this problem?

The js agent uses arrays to handle opt values. if you have an opt array you need to look for an array in an array.

would be null
[] would be an empty array
[[val,val]] would be an array with data in it

1 Like

Ok I solved the problem by removing the optional syntax from the Motoko tagList field.

// Motoko file
public type Entity = {
	tagList: [Text];
};
// Generatered Typescript file
export interface Entity {
    'tagList' : Array<string>,
};

In the end, it seems more relevant to have an empty Array rather than a null one.