Tuan Anh Tran
Tuan Anh Tran

Reputation: 7267

Declare custom type with TypeScript and how to test it?

I would like to declare a type which can either be object or Array

I've tried the following but using it in vscode doesn't show the autocomplete I want.

Btw, how do you test the declare types?

type ArrayTemplate = [ string, string | ObjectTemplate ]
type ObjectTemplate = {
    [key: string]: string | ObjectTemplate | ArrayTemplate
}

type CamaroTemplate = ObjectTemplate | ArrayTemplate

Upvotes: 0

Views: 178

Answers (1)

Josh
Josh

Reputation: 350

I've tested your types and they seem to be behaving how you have described. To use your types correctly and get VS Code autocompletes you must declare the types of your variables explicitly:

let t: ArrayTemplate = ["", ""];
let o: ObjectTemplate = { "TEST": t, "TEST2": "oops" }
t[1] = "another test";
console.log(o["TEST"]); // will log ["", "another test"]
console.log(o["TEST2"][""]); // undefined as type string has no property ""

Because you are using Union types you need to be careful that at runtime you are actually treating the variable correctly. For example the compiler will let me do the last line in that code snippet but at runtime it will resolve to undefined. In my opinion it is better to avoid union types as they are easy to get wrong at runtime.

Upvotes: 2

Related Questions