Issue
I use strings to represent my data and pass it around. Before using it I have to parse it and get the data out of string. I don't want to check for parse errors on runtime.
How can I give a special type to strings only produced by factory functions and make sure they fail on any other string types.
type MyData = string
let i = 0
function gen_id(): MyData {
return `hello__${i}`
}
function hello(_: MyData) {
console.log(_.split('__')[1])
}
hello(gen_id())
hello('world') // I want this to give compile error
Currently this doesn't produce an compile error.
Solution
TypeScript has support for string template literals:
type MyData = `${string}__${number}`
let i = 0
function gen_id(): MyData {
return `hello__${i}`
}
function hello(_: MyData) {
console.log(_.split('__')[1])
}
hello(gen_id())
hello('world') // Argument of type '"world"' is not assignable to parameter of type '`${string}__${number}`'.(2345)
Answered By - Slava Knyazev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.