简体   繁体   中英

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"
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM