Abhinay
Abhinay

Reputation: 21

Define type for filename string with extension in Typescript

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

Answers (2)

MatheusMol
MatheusMol

Reputation: 11

export type FileName = `${string}.svg` | `${string}.txt`

Upvotes: 1

Cerbrus
Cerbrus

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

Related Questions