TypeScript - specific string types

前端 未结 2 1211
一生所求
一生所求 2020-12-31 02:01

I\'m looking for a better way to distinguish between different types of strings in my program- for example, absolute paths and relative paths. I want to be able to have func

2条回答
  •  我在风中等你
    2020-12-31 02:21

    abstract class RelativePath extends String {
        public static createFromString(url: string): RelativePath {
            // validate if 'url' is indeed a relative path
            // for example, if it does not begin with '/'
            // ...
            return url as any;
        }
    
        private __relativePathFlag;
    }
    
    abstract class AbsolutePath extends String {
        public static createFromString(url: string): AbsolutePath {
            // validate if 'url' is indeed an absolute path
            // for example, if it begins with '/'
            // ...
            return url as any;
        }
    
        private __absolutePathFlag;
    }
    
    var path1 = RelativePath.createFromString("relative/path");
    var path2 = AbsolutePath.createFromString("/absolute/path");
    
    // Compile error: type 'AbsolutePath' is not assignable to type 'RelativePath'
    path1 = path2;
    
    console.log(typeof path1); // "string"
    console.log(typeof path2); // "string"
    console.log(path1.toUpperCase()); // "RELATIVE/PATH"
    

    This is just so wrong on every levels you could write a book about it... -- but it does work nicely, and it does get the job done.

    Since their creation is controlled as such, AbsolutePath and RelativePath instances are:

    • believed to be incompatible with each other by the TS compiler (because of the private property)
    • believed to be (inherit from) String by the TS compiler, allowing string functions to be called
    • actually real strings at runtime, providing runtime support for the supposedly inherited string functions

    This is analogous to a "faked inheritance" (as the TS compiler is told about an inheritance, but that inheritance does not exist at runtime) with additional data validation. Since no public members or methods were added, this should never cause unexpected runtime behavior, as the same supposed functionality exists both during compilation and runtime.

提交回复
热议问题