- Notifications
You must be signed in to change notification settings - Fork587
A collection of essential TypeScript types
License
CC0-1.0, MIT licenses found
Licenses found
sindresorhus/type-fest
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A collection of essential TypeScript types
Sindre Sorhus' open source work is supported by the community
Special thanks to:Add Single Sign-On (and more) in minutes instead of months.
Many of the types here should have been built-in. You can help by suggesting some of them to theTypeScript project.
Either add this package as a dependency or copy-paste the needed types. No credit required. 👌
PR welcome for additional commonly needed types and docs improvements. Read thecontributing guidelines first.
Help wanted with reviewingproposals andpull requests.
npm install type-fest
Requires TypeScript >=5.1
Works best with{strict: true}
in your tsconfig.
importtype{Except}from'type-fest';typeFoo={unicorn:string;rainbow:boolean;};typeFooWithoutRainbow=Except<Foo,'rainbow'>;//=> {unicorn: string}
Click the type names for complete docs.
Primitive
- Matches anyprimitive value.Class
- Matches aclass
.Constructor
- Matches aclass
constructor.AbstractClass
- Matches anabstract class
.AbstractConstructor
- Matches anabstract class
constructor.TypedArray
- Matches anytyped array, likeUint8Array
orFloat64Array
.ObservableLike
- Matches a value that is like anObservable.
EmptyObject
- Represents a strictly empty plain object, the{}
value.NonEmptyObject
- Represents an object with at least 1 non-optional key.UnknownRecord
- Represents an object withunknown
value. You probably want this instead of{}
.UnknownArray
- Represents an array withunknown
value.Except
- Create a type from an object type without certain keys. This is a stricter version ofOmit
.Writable
- Create a type that stripsreadonly
from the given type. Inverse ofReadonly<T>
.WritableDeep
- Create a deeply mutable version of anobject
/ReadonlyMap
/ReadonlySet
/ReadonlyArray
type. The inverse ofReadonlyDeep<T>
. UseWritable<T>
if you only need one level deep.Merge
- Merge two types into a new type. Keys of the second type overrides keys of the first type.MergeDeep
- Merge two objects or two arrays/tuples recursively into a new type.MergeExclusive
- Create a type that has mutually exclusive keys.OverrideProperties
- Override only existing properties of the given type. Similar toMerge
, but enforces that the original type has the properties you want to override.RequireAtLeastOne
- Create a type that requires at least one of the given keys.RequireExactlyOne
- Create a type that requires exactly a single key of the given keys and disallows more.RequireAllOrNone
- Create a type that requires all of the given keys or none of the given keys.RequireOneOrNone
- Create a type that requires exactly a single key of the given keys and disallows more, or none of the given keys.SingleKeyObject
- Create a type that only accepts an object with a single key.RequiredDeep
- Create a deeply required version of another type. UseRequired<T>
if you only need one level deep.PickDeep
- Pick properties from a deeply-nested object. UsePick<T>
if you only need one level deep.OmitDeep
- Omit properties from a deeply-nested object. UseOmit<T>
if you only need one level deep.OmitIndexSignature
- Omit any index signatures from the given object type, leaving only explicitly defined properties.PickIndexSignature
- Pick only index signatures from the given object type, leaving out all explicitly defined properties.PartialDeep
- Create a deeply optional version of another type. UsePartial<T>
if you only need one level deep.PartialOnUndefinedDeep
- Create a deep version of another type where all keys acceptingundefined
type are set to optional.UndefinedOnPartialDeep
- Create a deep version of another type where all optional keys are set to also acceptundefined
.ReadonlyDeep
- Create a deeply immutable version of anobject
/Map
/Set
/Array
type. UseReadonly<T>
if you only need one level deep.LiteralUnion
- Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround forMicrosoft/TypeScript#29729.Tagged
- Create atagged type that can supportmultiple tags andper-tag metadata. (This replaces the previousOpaque
type, which is now deprecated.)UnwrapTagged
- Get the untagged portion of a tagged type created withTagged
. (This replaces the previousUnwrapOpaque
type, which is now deprecated.)InvariantOf
- Create aninvariant type, which is a type that does not accept supertypes and subtypes.SetOptional
- Create a type that makes the given keys optional.SetReadonly
- Create a type that makes the given keys readonly.SetRequired
- Create a type that makes the given keys required.SetRequiredDeep
- LikeSetRequired
except it selects the keys deeply.SetNonNullable
- Create a type that makes the given keys non-nullable.ValueOf
- Create a union of the given object's values, and optionally specify which keys to get the values from.ConditionalKeys
- Extract keys from a shape where values extend the givenCondition
type.ConditionalPick
- LikePick
except it selects properties from a shape where the values extend the givenCondition
type.ConditionalPickDeep
- LikeConditionalPick
except that it selects the properties deeply.ConditionalExcept
- LikeOmit
except it removes properties from a shape where the values extend the givenCondition
type.UnionToIntersection
- Convert a union type to an intersection type.LiteralToPrimitive
- Convert aliteral type to theprimitive type it belongs to.LiteralToPrimitiveDeep
- LikeLiteralToPrimitive
except it converts literal types inside an object or array deeply.Stringified
- Create a type with the keys of the given type changed tostring
type.IterableElement
- Get the element type of anIterable
/AsyncIterable
. For example,Array
,Set
,Map
, generator, stream, etc.Entry
- Create a type that represents the type of an entry of a collection.Entries
- Create a type that represents the type of the entries of a collection.SetReturnType
- Create a function type with a return type of your choice and the same parameters as the given function type.SetParameterType
- Create a function that replaces some parameters with the given parameters.Simplify
- Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.SimplifyDeep
- Deeply simplifies an object type.Get
- Get a deeply-nested property from an object using a key path, likeLodash's.get()
function.StringKeyOf
- Get keys of the given type as strings.Schema
- Create a deep version of another object type where property values are recursively replaced into a given value type.Exact
- Create a type that does not allow extra properties.OptionalKeysOf
- Extract all optional keys from the given type.KeysOfUnion
- Create a union of all keys from a given type, even those exclusive to specific union members.HasOptionalKeys
- Create atrue
/false
type depending on whether the given type has any optional fields.RequiredKeysOf
- Extract all required keys from the given type.HasRequiredKeys
- Create atrue
/false
type depending on whether the given type has any required fields.ReadonlyKeysOf
- Extract all readonly keys from the given type.HasReadonlyKeys
- Create atrue
/false
type depending on whether the given type has any readonly fields.WritableKeysOf
- Extract all writable (non-readonly) keys from the given type.HasWritableKeys
- Create atrue
/false
type depending on whether the given type has any writable fields.Spread
- Mimic the type inferred by TypeScript when merging two objects or two arrays/tuples using the spread syntax.IsEqual
- Returns a boolean for whether the two given types are equal.TaggedUnion
- Create a union of types that share a common discriminant property.IntRange
- Generate a union of numbers (includes the start and excludes the end).IntClosedRange
- Generate a union of numbers (includes the start and the end).ArrayIndices
- Provides valid indices for a constant array or tuple.ArrayValues
- Provides all values for a constant array or tuple.ArraySplice
- Creates a new array type by adding or removing elements at a specified index range in the original array.ArrayTail
- Extracts the type of an array or tuple minus the first element.SetFieldType
- Create a type that changes the type of the given keys.Paths
- Generate a union of all possible paths to properties in the given object.SharedUnionFields
- Create a type with shared fields from a union of object types.SharedUnionFieldsDeep
- Create a type with shared fields from a union of object types, deeply traversing nested structures.AllUnionFields
- Create a type with all fields from a union of object types.DistributedOmit
- Omits keys from a type, distributing the operation over a union.DistributedPick
- Picks keys from a type, distributing the operation over a union.And
- Returns a boolean for whether two given types are both true.Or
- Returns a boolean for whether either of two given types are true.NonEmptyTuple
- Matches any non-empty tuple.FindGlobalType
- Tries to find the type of a global with the given name.FindGlobalInstanceType
- Tries to find one or more types from their globally-defined constructors.
For everyIsT
type (e.g.IsAny
), there is an associatedIfT
type that can help simplify conditional types. While theIsT
types return aboolean
, theIfT
types act like anIf
/Else
- they resolve to the givenTypeIfT
orTypeIfNotT
depending on whetherIsX
istrue
or not. By default,IfT
returns aboolean
:
typeIfAny<T,TypeIfAny=true,TypeIfNotAny=false>=(IsAny<T>extendstrue ?TypeIfAny :TypeIfNotAny);
importtype{IsAny,IfAny}from'type-fest';typeShouldBeTrue=IsAny<any>extendstrue ?true :false;//=> truetypeShouldBeFalse=IfAny<'not any'>;//=> falsetypeShouldBeNever=IfAny<'not any','not never','never'>;//=> 'never'
IsLiteral
- Returns a boolean for whether the given type is aliteral type.IsStringLiteral
- Returns a boolean for whether the given type is astring
literal type.IsNumericLiteral
- Returns a boolean for whether the given type is anumber
orbigint
literal type.IsBooleanLiteral
- Returns a boolean for whether the given type is atrue
orfalse
literal type.IsSymbolLiteral
- Returns a boolean for whether the given type is asymbol
literal type.IsAny
- Returns a boolean for whether the given type isany
. (Conditional version:IfAny
)IsNever
- Returns a boolean for whether the given type isnever
. (Conditional version:IfNever
)IsUnknown
- Returns a boolean for whether the given type isunknown
. (Conditional version:IfUnknown
)IsEmptyObject
- Returns a boolean for whether the type is strictly equal to an empty plain object, the{}
value. (Conditional version:IfEmptyObject
)IsNull
- Returns a boolean for whether the given type isnull
. (Conditional version:IfNull
)IsTuple
- Returns a boolean for whether the given array is a tuple.
Jsonify
- Transform a type to one that is assignable to theJsonValue
type.Jsonifiable
- Matches a value that can be losslessly converted to JSON.JsonPrimitive
- Matches a JSON primitive.JsonObject
- Matches a JSON object.JsonArray
- Matches a JSON array.JsonValue
- Matches any valid JSON value.
StructuredCloneable
- Matches a value that can be losslessly cloned usingstructuredClone
.
Promisable
- Create a type that represents either the value or the value wrapped inPromiseLike
.AsyncReturnType
- Unwrap the return type of a function that returns aPromise
.Asyncify
- Create an async version of the given function type.
Trim
- Remove leading and trailing spaces from a string.Split
- Represents an array of strings split using a given character or character set.Words
- Represents an array of strings split using a heuristic for detecting words.Replace
- Represents a string with some or all matches replaced by a replacement.StringSlice
- Returns a string slice of a given range, just likeString#slice()
.StringRepeat
- Returns a new string which contains the specified number of copies of a given string, just likeString#repeat()
.
Arrayable
- Create a type that represents either the value or an array of the value.Includes
- Returns a boolean for whether the given array includes the given item.Join
- Join an array of strings and/or numbers using the given string as a delimiter.ArraySlice
- Returns an array slice of a given range, just likeArray#slice()
.LastArrayElement
- Extracts the type of the last element of an array.FixedLengthArray
- Create a type that represents an array of the given type and length.MultidimensionalArray
- Create a type that represents a multidimensional array of the given type and dimensions.MultidimensionalReadonlyArray
- Create a type that represents a multidimensional readonly array of the given type and dimensions.ReadonlyTuple
- Create a type that represents a read-only tuple of the given type and length.TupleToUnion
- Convert a tuple/array into a union type of its elements.UnionToTuple
- Convert a union type into an unordered tuple type of its elements.TupleToObject
- Transforms a tuple into an object, mapping each tuple index to its corresponding type as a key-value pair.
PositiveInfinity
- Matches the hiddenInfinity
type.NegativeInfinity
- Matches the hidden-Infinity
type.Finite
- A finitenumber
.Integer
- Anumber
that is an integer.Float
- Anumber
that is not an integer.NegativeFloat
- A negative (-∞ < x < 0
)number
that is not an integer.Negative
- A negativenumber
/bigint
(-∞ < x < 0
)NonNegative
- A non-negativenumber
/bigint
(0 <= x < ∞
).NegativeInteger
- A negative (-∞ < x < 0
)number
that is an integer.NonNegativeInteger
- A non-negative (0 <= x < ∞
)number
that is an integer.IsNegative
- Returns a boolean for whether the given number is a negative number.IsFloat
- Returns a boolean for whether the given number is a float, like1.5
or-1.5
.IsInteger
- Returns a boolean for whether the given number is a integer, like-5
,1.0
or100
.GreaterThan
- Returns a boolean for whether a given number is greater than another number.GreaterThanOrEqual
- Returns a boolean for whether a given number is greater than or equal to another number.LessThan
- Returns a boolean for whether a given number is less than another number.LessThanOrEqual
- Returns a boolean for whether a given number is less than or equal to another number.Sum
- Returns the sum of two numbers.Subtract
- Returns the difference between two numbers.
CamelCase
- Convert a string literal to camel-case (fooBar
).CamelCasedProperties
- Convert object properties to camel-case (fooBar
).CamelCasedPropertiesDeep
- Convert object properties to camel-case recursively (fooBar
).KebabCase
- Convert a string literal to kebab-case (foo-bar
).KebabCasedProperties
- Convert a object properties to kebab-case recursively (foo-bar
).KebabCasedPropertiesDeep
- Convert object properties to kebab-case (foo-bar
).PascalCase
- Converts a string literal to pascal-case (FooBar
)PascalCasedProperties
- Converts object properties to pascal-case (FooBar
)PascalCasedPropertiesDeep
- Converts object properties to pascal-case (FooBar
)SnakeCase
- Convert a string literal to snake-case (foo_bar
).SnakeCasedProperties
- Convert object properties to snake-case (foo_bar
).SnakeCasedPropertiesDeep
- Convert object properties to snake-case recursively (foo_bar
).ScreamingSnakeCase
- Convert a string literal to screaming-snake-case (FOO_BAR
).DelimiterCase
- Convert a string literal to a custom string delimiter casing.DelimiterCasedProperties
- Convert object properties to a custom string delimiter casing.DelimiterCasedPropertiesDeep
- Convert object properties to a custom string delimiter casing recursively.
GlobalThis
- Declare locally scoped properties onglobalThis
.PackageJson
- Type fornpm'spackage.json
file. It also includes support forTypeScript Declaration Files.TsConfigJson
- Type forTypeScript'stsconfig.json
file.
If we decline a type addition, we will make sure to document the better solution here.
Diff
andSpread
- The pull request author didn't provide any real-world use-cases and the PR went stale. If you think this type is useful, provide some real-world use-cases and we might reconsider.Dictionary
- You only save a few characters (Dictionary<number>
vsRecord<string, number>
) fromRecord
, which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We haveMap
in JavaScript now.ExtractProperties
andExtractMethods
- The types violate the single responsibility principle. Instead, refine your types into more granular type hierarchies.Url2Json
- Inferring search parameters from a URL string is a cute idea, but not very useful in practice, since search parameters are usually dynamic and defined separately.Nullish
- The type only saves a couple of characters, not everyone knows what "nullish" means, and I'm also trying toget away fromnull
.TitleCase
- It's not solving a common need and is a better fit for a separate package.ExtendOr
andExtendAnd
- The benefits don't outweigh having to learn what they mean.PackageJsonExtras
- There are too many possible configurations that can be put intopackage.json
. If you would like to extendPackageJson
to support an additional configuration in your project, please see theExtending existing types section below.
If you know one of our types by a different name, add it here for discovery.
Prettify
- SeeSimplify
Expand
- SeeSimplify
PartialBy
- SeeSetOptional
RecordDeep
- SeeSchema
Mutable
- SeeWritable
RequireOnlyOne
,OneOf
- SeeRequireExactlyOne
AtMostOne
- SeeRequireOneOrNone
AllKeys
- SeeKeysOfUnion
Branded
- SeeTagged
Opaque
- SeeTagged
SetElement
- SeeIterableElement
SetEntry
- SeeIterableElement
SetValues
- SeeIterableElement
PickByTypes
- SeeConditionalPick
HomomorphicOmit
- SeeExcept
PackageJson
- There are a lot of tools that place extra configurations inside thepackage.json
file. You can extendPackageJson
to support these additional configurations.Example
importtype{PackageJsonasBasePackageJson}from'type-fest';importtype{Linter}from'eslint';typePackageJson=BasePackageJson&{eslintConfig?:Linter.Config};
- typed-query-selector - Enhances
document.querySelector
anddocument.querySelectorAll
with a template literal type that matches element types returned from an HTML element query selector. Linter.Config
- Definitions for theESLint configuration schema.
There are many advanced types most users don't know about.
Awaited<T>
- Extract the type of a value that aPromise
resolves to.Example
interfaceUser{id:number;name:string;age:number;}classUserApiService{asyncfetchUser(userId:number):Promise<User>{// Fetch the user data from the database.// The actual implementation might look like this:// const response = await fetch('/api/user/${userId}');// const data = response.json();// return data;return{id:1,name:'John Doe',age:30};}}typeFetchedUser=Awaited<ReturnType<UserApiService['fetchUser']>>;asyncfunctionhandleUserData(apiService:UserApiService,userId:number){try{constuser:FetchedUser=awaitapiService.fetchUser(userId);// After fetching user data, you can perform various actions such as updating the user interface,// caching the data for future use, or making additional API requests as needed.}catch(error){// Error handling}}constuserApiService=newUserApiService();handleUserData(userApiService,1);
Partial<T>
- Make all properties inT
optional.Example
interfaceNodeConfig{appName:string;port:number;}classNodeAppBuilder{privateconfiguration:NodeConfig={appName:'NodeApp',port:3000};privateupdateConfig<KeyextendskeyofNodeConfig>(key:Key,value:NodeConfig[Key]){this.configuration[key]=value;}config(config:Partial<NodeConfig>){typeNodeConfigKey=keyofNodeConfig;for(constkeyofObject.keys(config)asNodeConfigKey[]){constupdateValue=config[key];if(updateValue===undefined){continue;}this.updateConfig(key,updateValue);}returnthis;}}// `Partial<NodeConfig>`` allows us to provide only a part of the// NodeConfig interface.newNodeAppBuilder().config({appName:'ToDoApp'});
Required<T>
- Make all properties inT
required.Example
interfaceContactForm{email?:string;message?:string;}functionsubmitContactForm(formData:Required<ContactForm>){// Send the form data to the server.}submitContactForm({email:'ex@mple.com',message:'Hi! Could you tell me more about…',});// TypeScript error: missing property 'message'submitContactForm({email:'ex@mple.com',});
Readonly<T>
- Make all properties inT
readonly.Example
enumLogLevel{Off,Debug,Error,Fatal};interfaceLoggerConfig{name:string;level:LogLevel;}classLogger{config:Readonly<LoggerConfig>;constructor({name, level}:LoggerConfig){this.config={name, level};Object.freeze(this.config);}}constconfig:LoggerConfig={name:'MyApp',level:LogLevel.Debug};constlogger=newLogger(config);// TypeScript Error: cannot assign to read-only property.logger.config.level=LogLevel.Error;// We are able to edit config variable as we please.config.level=LogLevel.Error;
Pick<T, K>
- FromT
, pick a set of properties whose keys are in the unionK
.Example
interfaceArticle{title:string;thumbnail:string;content:string;}// Creates new type out of the `Article` interface composed// from the Articles' two properties: `title` and `thumbnail`.// `ArticlePreview = {title: string; thumbnail: string}`typeArticlePreview=Pick<Article,'title'|'thumbnail'>;// Render a list of articles using only title and description.functionrenderArticlePreviews(previews:ArticlePreview[]):HTMLElement{constarticles=document.createElement('div');for(constpreviewofpreviews){// Append preview to the articles.}returnarticles;}constarticles=renderArticlePreviews([{title:'TypeScript tutorial!',thumbnail:'/assets/ts.jpg'}]);
Record<K, T>
- Construct a type with a set of propertiesK
of typeT
.Example
// Positions of employees in our company.typeMemberPosition='intern'|'developer'|'tech-lead';// Interface describing properties of a single employee.interfaceEmployee{firstName:string;lastName:string;yearsOfExperience:number;}// Create an object that has all possible `MemberPosition` values set as keys.// Those keys will store a collection of Employees of the same position.constteam:Record<MemberPosition,Employee[]>={intern:[],developer:[],'tech-lead':[],};// Our team has decided to help John with his dream of becoming Software Developer.team.intern.push({firstName:'John',lastName:'Doe',yearsOfExperience:0});// `Record` forces you to initialize all of the property keys.// TypeScript Error: "tech-lead" property is missingconstteamEmpty:Record<MemberPosition,null>={intern:null,developer:null,};
Exclude<T, U>
- Exclude fromT
those types that are assignable toU
.Example
interfaceServerConfig{port:null|string|number;}typeRequestHandler=(request:Request,response:Response)=>void;// Exclude `null` type from `null | string | number`.// In case the port is equal to `null`, we will use default value.functiongetPortValue(port:Exclude<ServerConfig['port'],null>):number{if(typeofport==='string'){returnparseInt(port,10);}returnport;}functionstartServer(handler:RequestHandler,config:ServerConfig):void{constserver=require('http').createServer(handler);constport=config.port===null ?3000 :getPortValue(config.port);server.listen(port);}
Extract<T, U>
- Extract fromT
those types that are assignable toU
.Example
declarefunctionuniqueId():number;constID=Symbol('ID');interfacePerson{[ID]:number;name:string;age:number;}// Allows changing the person data as long as the property key is of string type.functionchangePersonData<ObjextendsPerson,KeyextendsExtract<keyofPerson,string>,ValueextendsObj[Key]>(obj:Obj,key:Key,value:Value):void{obj[key]=value;}// Tiny Andrew was born.constandrew={[ID]:uniqueId(),name:'Andrew',age:0,};// Cool, we're fine with that.changePersonData(andrew,'name','Pony');// Government didn't like the fact that you wanted to change your identity.changePersonData(andrew,ID,uniqueId());
NonNullable<T>
- Excludenull
andundefined
fromT
.Example
Works withstrictNullChecks
set totrue
.typePortNumber=string|number|null;/** Part of a class definition that is used to build a server */classServerBuilder{portNumber!:NonNullable<PortNumber>;port(this:ServerBuilder,port:PortNumber):ServerBuilder{if(port==null){this.portNumber=8000;}else{this.portNumber=port;}returnthis;}}constserverBuilder=newServerBuilder();serverBuilder.port('8000')// portNumber = '8000'.port(null)// portNumber = 8000.port(3000);// portNumber = 3000// TypeScript errorserverBuilder.portNumber=null;
Parameters<T>
- Obtain the parameters of a function type in a tuple.Example
functionshuffle(input:any[]):void{// Mutate array randomly changing its' elements indexes.}functioncallNTimes<Fnextends(...arguments_:any[])=>any>(func:Fn,callCount:number){// Type that represents the type of the received function parameters.typeFunctionParameters=Parameters<Fn>;returnfunction(...arguments_:FunctionParameters){for(leti=0;i<callCount;i++){func(...arguments_);}}}constshuffleTwice=callNTimes(shuffle,2);
ConstructorParameters<T>
- Obtain the parameters of a constructor function type in a tuple.Example
classArticleModel{title:string;content?:string;constructor(title:string){this.title=title;}}classInstanceCache<Textends(new(...arguments_:any[])=>any)>{privateClassConstructor:T;privatecache:Map<string,InstanceType<T>>=newMap();constructor(ctr:T){this.ClassConstructor=ctr;}getInstance(...arguments_:ConstructorParameters<T>):InstanceType<T>{consthash=this.calculateArgumentsHash(...arguments_);constexistingInstance=this.cache.get(hash);if(existingInstance!==undefined){returnexistingInstance;}returnnewthis.ClassConstructor(...arguments_);}privatecalculateArgumentsHash(...arguments_:any[]):string{// Calculate hash.return'hash';}}constarticleCache=newInstanceCache(ArticleModel);constamazonArticle=articleCache.getInstance('Amazon forests burning!');
ReturnType<T>
- Obtain the return type of a function type.Example
/** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */functionmapIter<Elem,Funcextends(elem:Elem)=>any,RetextendsReturnType<Func>>(iter:Iterable<Elem>,callback:Func):Ret[]{constmapped:Ret[]=[];for(constelemofiter){mapped.push(callback(elem));}returnmapped;}constsetObject:Set<string>=newSet();constmapObject:Map<number,string>=newMap();mapIter(setObject,(value:string)=>value.indexOf('Foo'));// number[]mapIter(mapObject,([key,value]:[number,string])=>{returnkey%2===0 ?value :'Odd';});// string[]
InstanceType<T>
- Obtain the instance type of a constructor function type.Example
classIdleService{doNothing():void{}}classNews{title:string;content:string;constructor(title:string,content:string){this.title=title;this.content=content;}}constinstanceCounter:Map<Function,number>=newMap();interfaceConstructor{new(...arguments_:any[]):any;}// Keep track how many instances of `Constr` constructor have been created.functiongetInstance<ConstrextendsConstructor,ArgumentsextendsConstructorParameters<Constr>>(constructor:Constr, ...arguments_:Arguments):InstanceType<Constr>{letcount=instanceCounter.get(constructor)||0;constinstance=newconstructor(...arguments_);instanceCounter.set(constructor,count+1);console.log(`Created${count+1} instances of${Constr.name} class`);returninstance;}constidleService=getInstance(IdleService);// Will log: `Created 1 instances of IdleService class`constnewsEntry=getInstance(News,'New ECMAScript proposals!','Last month...');// Will log: `Created 1 instances of News class`
Omit<T, K>
- Constructs a type by picking all properties from T and then removing K.Example
interfaceAnimal{imageUrl:string;species:string;images:string[];paragraphs:string[];}// Creates new type with all properties of the `Animal` interface// except 'images' and 'paragraphs' properties. We can use this// type to render small hover tooltip for a wiki entry list.typeAnimalShortInfo=Omit<Animal,'images'|'paragraphs'>;functionrenderAnimalHoverInfo(animals:AnimalShortInfo[]):HTMLElement{constcontainer=document.createElement('div');// Internal implementation.returncontainer;}
Uppercase<S extends string>
- Transforms every character in a string into uppercase.Example
typeT=Uppercase<'hello'>;// 'HELLO'typeT2=Uppercase<'foo'|'bar'>;// 'FOO' | 'BAR'typeT3<Sextendsstring>=Uppercase<`aB${S}`>;typeT4=T3<'xYz'>;// 'ABXYZ'typeT5=Uppercase<string>;// stringtypeT6=Uppercase<any>;// anytypeT7=Uppercase<never>;// nevertypeT8=Uppercase<42>;// Error, type 'number' does not satisfy the constraint 'string'
Lowercase<S extends string>
- Transforms every character in a string into lowercase.Example
typeT=Lowercase<'HELLO'>;// 'hello'typeT2=Lowercase<'FOO'|'BAR'>;// 'foo' | 'bar'typeT3<Sextendsstring>=Lowercase<`aB${S}`>;typeT4=T3<'xYz'>;// 'abxyz'typeT5=Lowercase<string>;// stringtypeT6=Lowercase<any>;// anytypeT7=Lowercase<never>;// nevertypeT8=Lowercase<42>;// Error, type 'number' does not satisfy the constraint 'string'
Capitalize<S extends string>
- Transforms the first character in a string into uppercase.Example
typeT=Capitalize<'hello'>;// 'Hello'typeT2=Capitalize<'foo'|'bar'>;// 'Foo' | 'Bar'typeT3<Sextendsstring>=Capitalize<`aB${S}`>;typeT4=T3<'xYz'>;// 'ABxYz'typeT5=Capitalize<string>;// stringtypeT6=Capitalize<any>;// anytypeT7=Capitalize<never>;// nevertypeT8=Capitalize<42>;// Error, type 'number' does not satisfy the constraint 'string'
Uncapitalize<S extends string>
- Transforms the first character in a string into lowercase.Example
typeT=Uncapitalize<'Hello'>;// 'hello'typeT2=Uncapitalize<'Foo'|'Bar'>;// 'foo' | 'bar'typeT3<Sextendsstring>=Uncapitalize<`AB${S}`>;typeT4=T3<'xYz'>;// 'aBxYz'typeT5=Uncapitalize<string>;// stringtypeT6=Uncapitalize<any>;// anytypeT7=Uncapitalize<never>;// nevertypeT8=Uncapitalize<42>;// Error, type 'number' does not satisfy the constraint 'string'
You can find some examples in theTypeScript docs.
- Sindre Sorhus
- Haozheng Li
- Som Shekhar Mukherjee
- Jarek Radosz
- Dimitri Benin
- Pelle Wessman
- Sébastien Mischler
SPDX-License-Identifier: (MIT OR CC0-1.0)
About
A collection of essential TypeScript types