Extending A String In Typescript
Solution 1:
type narrowedString = "foo" | "bar"
// type ExtendsString = truetype ExtendsString = "foo" extends string ? true : false
"foo" and "bar" extend both the string type. For example that is useful, when you want to define enum like data structures (without the built in TypeScript enum type) or constants.
When a function offers a generic type parameter which extends string like T extends string
, you can use that to enforce strong typing for your enums/constants.
function doSomething<T extendsstring>(t: T): {a: T} {
...
}
// invoke itdoSomething("foo"asconst) // return {a: "foo"}
Don't make the mistake to lump extends
in TypeScript's typesystem together with extends
from ES classes - they are two complete distinct operators.
class extends
corresponds to instanceof
and exists in the runtime as a construct, whereas in the type system extends
e.g. occurs with Conditional types,can be translated with "is assignable to" and is only for compile time.
Update:
You can find out more about String Literal Types in the TypeScript docs.
Solution 2:
Here is a simple example of how you might extend a string and how hard coding the type would break it.
typeFoo = string & Partial<{ meta: string }>
constfoo: Foo = 'foo';
foo.meta = 'this string is important';
functionhardCoded(x: string): string {
return x;
}
hardCoded(foo).meta; // this is an errorfunction generic<X extendsstring>(x: X): X {
return x;
}
generic(foo).meta; // but this works
Post a Comment for "Extending A String In Typescript"