Skip to main content

String Manipulation

It is important to understand how Typescript string literal works in order for Typescript to understand the type of your path and key.

note

This is for keys only, not values.

Convert number to ${number}

Let say we have something like this

import {
MetaTypeCreator,
NumericKeyRecord,
createRef,
update,
getDatabase,
} from 'firesagejs'

type Example = MetaTypeCreator<{
a: NumericKeyRecord<boolean>
}>

const ref = createRef<Example>(getDatabase())

const numericKey = 123

update(ref('a'), [numericKey], [true]) // type error, expecting numeric string but number instead!

update(ref('a'), [numericKey.toString()], [true]) // type error, expecting numeric string but got string instead!

update(ref('a'), [`${numericKey}`], [true]) // working, because `${number}` is numeric string
how to convert number to numeric string safely

Every path and key must be string, so number type is not possible.

the return type of toString is string, but FireSage needs narrowed type to tell apart non-numeric and numeric string.

String Concatenation

import {
MetaTypeCreator,
NumericKeyRecord,
createRef,
getDatabase,
} from 'firesagejs'

type Example = MetaTypeCreator<{
a: { b: NumericKeyRecord<boolean>; c: Record<string, 1 | 2 | 3> }
}>

const ref = createRef<Example>(getDatabase())

const numericKey = 123
const nonNumericKey = 'x7y8z9'

const ref1 = ref('a/b/' + `${numericKey}`) // type error, type is string!

const ref2 = ref('a/c/' + `${nonNumericKey}`) // type error, type is string!

const ref3 = ref(`a/b/${numericKey}`) //ok, type is `a/b/123`!

const ref4 = ref(`a/c/${nonNumericKey}`) // ok, type is `a/c/x7y8z9`!
how to concate string safely

Do not use + to concate the string because + output string type. Always use template string to concate string.