Function near_syn::ts::ts_type[][src]

pub fn ts_type(ty: &Type) -> String

Return the TypeScript equivalent type of the Rust type represented by ty. Rust primitives types and String are included.

use syn::parse_str;
use near_syn::ts::ts_type;

assert_eq!(ts_type(&parse_str("bool").unwrap()), "boolean");
assert_eq!(ts_type(&parse_str("i8").unwrap()), "number");
assert_eq!(ts_type(&parse_str("u8").unwrap()), "number");
assert_eq!(ts_type(&parse_str("i16").unwrap()), "number");
assert_eq!(ts_type(&parse_str("u16").unwrap()), "number");
assert_eq!(ts_type(&parse_str("i32").unwrap()), "number");
assert_eq!(ts_type(&parse_str("u32").unwrap()), "number");
assert_eq!(ts_type(&parse_str("String").unwrap()), "string");

Rust standard and collections types, e.g., Option, Vec and HashMap, are included in the translation.

assert_eq!(ts_type(&parse_str("Option<U64>").unwrap()), "U64|null");
assert_eq!(ts_type(&parse_str("Option<String>").unwrap()), "string|null");
assert_eq!(ts_type(&parse_str("Vec<ValidAccountId>").unwrap()), "ValidAccountId[]");
assert_eq!(ts_type(&parse_str("HashSet<ValidAccountId>").unwrap()), "ValidAccountId[]");
assert_eq!(ts_type(&parse_str("BTreeSet<ValidAccountId>").unwrap()), "ValidAccountId[]");
assert_eq!(ts_type(&parse_str("HashMap<AccountId, U128>").unwrap()), "Record<AccountId, U128>");
assert_eq!(ts_type(&parse_str("BTreeMap<AccountId, U128>").unwrap()), "Record<AccountId, U128>");

Rust nested types are converted to TypeScript as well.

assert_eq!(ts_type(&parse_str("HashMap<AccountId, Vec<U128>>").unwrap()), "Record<AccountId, U128[]>");
assert_eq!(ts_type(&parse_str("Vec<Option<U128>>").unwrap()), "(U128|null)[]");
assert_eq!(ts_type(&parse_str("Option<Vec<U128>>").unwrap()), "U128[]|null");
assert_eq!(ts_type(&parse_str("Option<Option<U64>>").unwrap()), "U64|null|null");
assert_eq!(ts_type(&parse_str("Vec<Vec<U64>>").unwrap()), "U64[][]");
assert_eq!(ts_type(&parse_str("(U64)").unwrap()), "U64");
assert_eq!(ts_type(&parse_str("(U64, String, Vec<u32>)").unwrap()), "[U64, string, number[]]");

assert_eq!(ts_type(&parse_str("()").unwrap()), "void");
// assert_eq!(ts_type(&parse_str("std::vec::Vec<U64>").unwrap()), "U64[]");

Panics

Panics when standard library generics types are used incorrectly. For example Option or HashMap<U64>. This situation can only happen on Rust source files that were not type-checked by rustc.