Reputation: 21
I want to define the type for a filename field in my object. It'll have a string containing name of the file along with extension, of the file uploaded by user.
For example:
{
icon: "my_icon.svg"`
}
I want to define a type that will enforce that the filenames always end with ".svg". Right now I am doing this (and needless to say, it's not working)
{
icon: string & ".svg"
}
Upvotes: 1
Views: 1512
Reputation: 72947
You can use template literals for that:
let x: `${string}.svg`;
x = 'foo'; // Error: Type '"foo"' is not assignable to type '`${string}.svg`'.
x = 'bar.svg'; // This is ok
Upvotes: 4