Installations
npm install type-fest
Score
99.6
Supply Chain
99.6
Quality
94.5
Maintenance
100
Vulnerability
99.6
License
Releases
Contributors
Developer
sindresorhus
Developer Guide
Module System
Unable to determine the module system for this package.
Min. Node Version
>=16
Typescript Support
Yes
Node Version
23.3.0
NPM Version
10.9.0
Statistics
14,424 Stars
664 Commits
549 Forks
51 Watching
1 Branches
169 Contributors
Updated on 28 Nov 2024
Languages
TypeScript (99.7%)
JavaScript (0.3%)
Total Downloads
Cumulative downloads
Total Downloads
25,081,177,997
Last day
-7.8%
34,765,721
Compared to previous day
Last week
1.7%
203,658,842
Compared to previous week
Last month
12.3%
833,955,870
Compared to previous month
Last year
24.3%
8,510,748,693
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
5
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 the TypeScript 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 the contributing guidelines first.
Help wanted with reviewing proposals and pull requests.
Install
1npm install type-fest
Requires TypeScript >=5.1
Works best with {strict: true}
in your tsconfig.
Usage
1import type {Except} from 'type-fest'; 2 3type Foo = { 4 unicorn: string; 5 rainbow: boolean; 6}; 7 8type FooWithoutRainbow = Except<Foo, 'rainbow'>; 9//=> {unicorn: string}
API
Click the type names for complete docs.
Basic
Primitive
- Matches any primitive value.Class
- Matches aclass
.Constructor
- Matches aclass
constructor.AbstractClass
- Matches anabstract class
.AbstractConstructor
- Matches anabstract class
constructor.TypedArray
- Matches any typed array, likeUint8Array
orFloat64Array
.ObservableLike
- Matches a value that is like an Observable.
Utilities
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 for Microsoft/TypeScript#29729.Tagged
- Create a tagged type that can support multiple tags and per-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 an invariant 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.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 a literal type to the primitive 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, like Lodash'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).IntRange
- Generate a union of numbers.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.SharedUnionFieldsDeep
- Create a type with shared fields from a union of object types, deeply traversing nested structures.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.
Type Guard
IsType
vs. IfType
For every IsT
type (e.g. IsAny
), there is an associated IfT
type that can help simplify conditional types. While the IsT
types return a boolean
, the IfT
types act like an If
/Else
- they resolve to the given TypeIfT
or TypeIfNotT
depending on whether IsX
is true
or not. By default, IfT
returns a boolean
:
1type IfAny<T, TypeIfAny = true, TypeIfNotAny = false> = ( 2 IsAny<T> extends true ? TypeIfAny : TypeIfNotAny 3);
Usage
1import type {IsAny, IfAny} from 'type-fest'; 2 3type ShouldBeTrue = IsAny<any> extends true ? true : false; 4//=> true 5 6type ShouldBeFalse = IfAny<'not any'>; 7//=> false 8 9type ShouldBeNever = IfAny<'not any', 'not never', 'never'>; 10//=> 'never'
IsLiteral
- Returns a boolean for whether the given type is a literal 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
)
JSON
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.
Structured clone
StructuredCloneable
- Matches a value that can be losslessly cloned usingstructuredClone
.
Async
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.
String
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()
.
Array
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.
Numeric
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.
Change case
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.
Miscellaneous
GlobalThis
- Declare locally scoped properties onglobalThis
.PackageJson
- Type for npm'spackage.json
file. It also includes support for TypeScript Declaration Files.TsConfigJson
- Type for TypeScript'stsconfig.json
file.
Declined types
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 to get 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 the Extending existing types section below.
Alternative type names
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
Tips
Extending existing types
-
PackageJson
- There are a lot of tools that place extra configurations inside thepackage.json
file. You can extendPackageJson
to support these additional configurations.Example
1import type {PackageJson as BasePackageJson} from 'type-fest'; 2import type {Linter} from 'eslint'; 3 4type PackageJson = BasePackageJson & {eslintConfig?: Linter.Config};
Related
- 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 the ESLint configuration schema.
Built-in types
There are many advanced types most users don't know about.
-
Awaited<T>
- Extract the type of a value that aPromise
resolves to.Example
1interface User { 2 id: number; 3 name: string; 4 age: number; 5} 6 7class UserApiService { 8 async fetchUser(userId: number): Promise<User> { 9 // Fetch the user data from the database. 10 // The actual implementation might look like this: 11 // const response = await fetch('/api/user/${userId}'); 12 // const data = response.json(); 13 // return data; 14 return { 15 id: 1, 16 name: 'John Doe', 17 age: 30 18 }; 19 } 20} 21 22type FetchedUser = Awaited<ReturnType<UserApiService['fetchUser']>>; 23 24async function handleUserData(apiService: UserApiService, userId: number) { 25 try { 26 const user: FetchedUser = await apiService.fetchUser(userId); 27 // After fetching user data, you can perform various actions such as updating the user interface, 28 // caching the data for future use, or making additional API requests as needed. 29 } catch (error) { 30 // Error handling 31 } 32} 33 34const userApiService = new UserApiService(); 35handleUserData(userApiService, 1);
-
Partial<T>
- Make all properties inT
optional.Example
1interface NodeConfig { 2 appName: string; 3 port: number; 4} 5 6class NodeAppBuilder { 7 private configuration: NodeConfig = { 8 appName: 'NodeApp', 9 port: 3000 10 }; 11 12 private updateConfig<Key extends keyof NodeConfig>(key: Key, value: NodeConfig[Key]) { 13 this.configuration[key] = value; 14 } 15 16 config(config: Partial<NodeConfig>) { 17 type NodeConfigKey = keyof NodeConfig; 18 19 for (const key of Object.keys(config) as NodeConfigKey[]) { 20 const updateValue = config[key]; 21 22 if (updateValue === undefined) { 23 continue; 24 } 25 26 this.updateConfig(key, updateValue); 27 } 28 29 return this; 30 } 31} 32 33// `Partial<NodeConfig>`` allows us to provide only a part of the 34// NodeConfig interface. 35new NodeAppBuilder().config({appName: 'ToDoApp'});
-
Required<T>
- Make all properties inT
required.Example
1interface ContactForm { 2 email?: string; 3 message?: string; 4} 5 6function submitContactForm(formData: Required<ContactForm>) { 7 // Send the form data to the server. 8} 9 10submitContactForm({ 11 email: 'ex@mple.com', 12 message: 'Hi! Could you tell me more about…', 13}); 14 15// TypeScript error: missing property 'message' 16submitContactForm({ 17 email: 'ex@mple.com', 18});
-
Readonly<T>
- Make all properties inT
readonly.Example
1enum LogLevel { 2 Off, 3 Debug, 4 Error, 5 Fatal 6}; 7 8interface LoggerConfig { 9 name: string; 10 level: LogLevel; 11} 12 13class Logger { 14 config: Readonly<LoggerConfig>; 15 16 constructor({name, level}: LoggerConfig) { 17 this.config = {name, level}; 18 Object.freeze(this.config); 19 } 20} 21 22const config: LoggerConfig = { 23 name: 'MyApp', 24 level: LogLevel.Debug 25}; 26 27const logger = new Logger(config); 28 29// TypeScript Error: cannot assign to read-only property. 30logger.config.level = LogLevel.Error; 31 32// We are able to edit config variable as we please. 33config.level = LogLevel.Error;
-
Pick<T, K>
- FromT
, pick a set of properties whose keys are in the unionK
.Example
1interface Article { 2 title: string; 3 thumbnail: string; 4 content: string; 5} 6 7// Creates new type out of the `Article` interface composed 8// from the Articles' two properties: `title` and `thumbnail`. 9// `ArticlePreview = {title: string; thumbnail: string}` 10type ArticlePreview = Pick<Article, 'title' | 'thumbnail'>; 11 12// Render a list of articles using only title and description. 13function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement { 14 const articles = document.createElement('div'); 15 16 for (const preview of previews) { 17 // Append preview to the articles. 18 } 19 20 return articles; 21} 22 23const articles = renderArticlePreviews([ 24 { 25 title: 'TypeScript tutorial!', 26 thumbnail: '/assets/ts.jpg' 27 } 28]);
-
Record<K, T>
- Construct a type with a set of propertiesK
of typeT
.Example
1// Positions of employees in our company. 2type MemberPosition = 'intern' | 'developer' | 'tech-lead'; 3 4// Interface describing properties of a single employee. 5interface Employee { 6 firstName: string; 7 lastName: string; 8 yearsOfExperience: number; 9} 10 11// Create an object that has all possible `MemberPosition` values set as keys. 12// Those keys will store a collection of Employees of the same position. 13const team: Record<MemberPosition, Employee[]> = { 14 intern: [], 15 developer: [], 16 'tech-lead': [], 17}; 18 19// Our team has decided to help John with his dream of becoming Software Developer. 20team.intern.push({ 21 firstName: 'John', 22 lastName: 'Doe', 23 yearsOfExperience: 0 24}); 25 26// `Record` forces you to initialize all of the property keys. 27// TypeScript Error: "tech-lead" property is missing 28const teamEmpty: Record<MemberPosition, null> = { 29 intern: null, 30 developer: null, 31};
-
Exclude<T, U>
- Exclude fromT
those types that are assignable toU
.Example
1interface ServerConfig { 2 port: null | string | number; 3} 4 5type RequestHandler = (request: Request, response: Response) => void; 6 7// Exclude `null` type from `null | string | number`. 8// In case the port is equal to `null`, we will use default value. 9function getPortValue(port: Exclude<ServerConfig['port'], null>): number { 10 if (typeof port === 'string') { 11 return parseInt(port, 10); 12 } 13 14 return port; 15} 16 17function startServer(handler: RequestHandler, config: ServerConfig): void { 18 const server = require('http').createServer(handler); 19 20 const port = config.port === null ? 3000 : getPortValue(config.port); 21 server.listen(port); 22}
-
Extract<T, U>
- Extract fromT
those types that are assignable toU
.Example
1declare function uniqueId(): number; 2 3const ID = Symbol('ID'); 4 5interface Person { 6 [ID]: number; 7 name: string; 8 age: number; 9} 10 11// Allows changing the person data as long as the property key is of string type. 12function changePersonData< 13 Obj extends Person, 14 Key extends Extract<keyof Person, string>, 15 Value extends Obj[Key] 16> (obj: Obj, key: Key, value: Value): void { 17 obj[key] = value; 18} 19 20// Tiny Andrew was born. 21const andrew = { 22 [ID]: uniqueId(), 23 name: 'Andrew', 24 age: 0, 25}; 26 27// Cool, we're fine with that. 28changePersonData(andrew, 'name', 'Pony'); 29 30// Government didn't like the fact that you wanted to change your identity. 31changePersonData(andrew, ID, uniqueId());
-
NonNullable<T>
- Excludenull
andundefined
fromT
.Example
Works withstrictNullChecks
set totrue
.1type PortNumber = string | number | null; 2 3/** Part of a class definition that is used to build a server */ 4class ServerBuilder { 5 portNumber!: NonNullable<PortNumber>; 6 7 port(this: ServerBuilder, port: PortNumber): ServerBuilder { 8 if (port == null) { 9 this.portNumber = 8000; 10 } else { 11 this.portNumber = port; 12 } 13 14 return this; 15 } 16} 17 18const serverBuilder = new ServerBuilder(); 19 20serverBuilder 21 .port('8000') // portNumber = '8000' 22 .port(null) // portNumber = 8000 23 .port(3000); // portNumber = 3000 24 25// TypeScript error 26serverBuilder.portNumber = null;
-
Parameters<T>
- Obtain the parameters of a function type in a tuple.Example
1function shuffle(input: any[]): void { 2 // Mutate array randomly changing its' elements indexes. 3} 4 5function callNTimes<Fn extends (...arguments_: any[]) => any> (func: Fn, callCount: number) { 6 // Type that represents the type of the received function parameters. 7 type FunctionParameters = Parameters<Fn>; 8 9 return function (...arguments_: FunctionParameters) { 10 for (let i = 0; i < callCount; i++) { 11 func(...arguments_); 12 } 13 } 14} 15 16const shuffleTwice = callNTimes(shuffle, 2);
-
ConstructorParameters<T>
- Obtain the parameters of a constructor function type in a tuple.Example
1class ArticleModel { 2 title: string; 3 content?: string; 4 5 constructor(title: string) { 6 this.title = title; 7 } 8} 9 10class InstanceCache<T extends (new (...arguments_: any[]) => any)> { 11 private ClassConstructor: T; 12 private cache: Map<string, InstanceType<T>> = new Map(); 13 14 constructor (ctr: T) { 15 this.ClassConstructor = ctr; 16 } 17 18 getInstance (...arguments_: ConstructorParameters<T>): InstanceType<T> { 19 const hash = this.calculateArgumentsHash(...arguments_); 20 21 const existingInstance = this.cache.get(hash); 22 if (existingInstance !== undefined) { 23 return existingInstance; 24 } 25 26 return new this.ClassConstructor(...arguments_); 27 } 28 29 private calculateArgumentsHash(...arguments_: any[]): string { 30 // Calculate hash. 31 return 'hash'; 32 } 33} 34 35const articleCache = new InstanceCache(ArticleModel); 36const amazonArticle = articleCache.getInstance('Amazon forests burning!');
-
ReturnType<T>
- Obtain the return type of a function type.Example
1/** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */ 2function mapIter< 3 Elem, 4 Func extends (elem: Elem) => any, 5 Ret extends ReturnType<Func> 6>(iter: Iterable<Elem>, callback: Func): Ret[] { 7 const mapped: Ret[] = []; 8 9 for (const elem of iter) { 10 mapped.push(callback(elem)); 11 } 12 13 return mapped; 14} 15 16const setObject: Set<string> = new Set(); 17const mapObject: Map<number, string> = new Map(); 18 19mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[] 20 21mapIter(mapObject, ([key, value]: [number, string]) => { 22 return key % 2 === 0 ? value : 'Odd'; 23}); // string[]
-
InstanceType<T>
- Obtain the instance type of a constructor function type.Example
1class IdleService { 2 doNothing (): void {} 3} 4 5class News { 6 title: string; 7 content: string; 8 9 constructor(title: string, content: string) { 10 this.title = title; 11 this.content = content; 12 } 13} 14 15const instanceCounter: Map<Function, number> = new Map(); 16 17interface Constructor { 18 new(...arguments_: any[]): any; 19} 20 21// Keep track how many instances of `Constr` constructor have been created. 22function getInstance< 23 Constr extends Constructor, 24 Arguments extends ConstructorParameters<Constr> 25>(constructor: Constr, ...arguments_: Arguments): InstanceType<Constr> { 26 let count = instanceCounter.get(constructor) || 0; 27 28 const instance = new constructor(...arguments_); 29 30 instanceCounter.set(constructor, count + 1); 31 32 console.log(`Created ${count + 1} instances of ${Constr.name} class`); 33 34 return instance; 35} 36 37 38const idleService = getInstance(IdleService); 39// Will log: `Created 1 instances of IdleService class` 40const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...'); 41// 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
1interface Animal { 2 imageUrl: string; 3 species: string; 4 images: string[]; 5 paragraphs: string[]; 6} 7 8// Creates new type with all properties of the `Animal` interface 9// except 'images' and 'paragraphs' properties. We can use this 10// type to render small hover tooltip for a wiki entry list. 11type AnimalShortInfo = Omit<Animal, 'images' | 'paragraphs'>; 12 13function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement { 14 const container = document.createElement('div'); 15 // Internal implementation. 16 return container; 17}
-
Uppercase<S extends string>
- Transforms every character in a string into uppercase.Example
1type T = Uppercase<'hello'>; // 'HELLO' 2 3type T2 = Uppercase<'foo' | 'bar'>; // 'FOO' | 'BAR' 4 5type T3<S extends string> = Uppercase<`aB${S}`>; 6type T4 = T3<'xYz'>; // 'ABXYZ' 7 8type T5 = Uppercase<string>; // string 9type T6 = Uppercase<any>; // any 10type T7 = Uppercase<never>; // never 11type T8 = Uppercase<42>; // Error, type 'number' does not satisfy the constraint 'string'
-
Lowercase<S extends string>
- Transforms every character in a string into lowercase.Example
1type T = Lowercase<'HELLO'>; // 'hello' 2 3type T2 = Lowercase<'FOO' | 'BAR'>; // 'foo' | 'bar' 4 5type T3<S extends string> = Lowercase<`aB${S}`>; 6type T4 = T3<'xYz'>; // 'abxyz' 7 8type T5 = Lowercase<string>; // string 9type T6 = Lowercase<any>; // any 10type T7 = Lowercase<never>; // never 11type T8 = 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
1type T = Capitalize<'hello'>; // 'Hello' 2 3type T2 = Capitalize<'foo' | 'bar'>; // 'Foo' | 'Bar' 4 5type T3<S extends string> = Capitalize<`aB${S}`>; 6type T4 = T3<'xYz'>; // 'ABxYz' 7 8type T5 = Capitalize<string>; // string 9type T6 = Capitalize<any>; // any 10type T7 = Capitalize<never>; // never 11type T8 = 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
1type T = Uncapitalize<'Hello'>; // 'hello' 2 3type T2 = Uncapitalize<'Foo' | 'Bar'>; // 'foo' | 'bar' 4 5type T3<S extends string> = Uncapitalize<`AB${S}`>; 6type T4 = T3<'xYz'>; // 'aBxYz' 7 8type T5 = Uncapitalize<string>; // string 9type T6 = Uncapitalize<any>; // any 10type T7 = Uncapitalize<never>; // never 11type T8 = Uncapitalize<42>; // Error, type 'number' does not satisfy the constraint 'string'
You can find some examples in the TypeScript docs.
Maintainers
License
SPDX-License-Identifier: (MIT OR CC0-1.0)
No vulnerabilities found.
Reason
18 commit(s) and 12 issue activity found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
- Info: security policy file detected: .github/security.md:1
- Info: Found linked content: .github/security.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: .github/security.md:1
- Info: Found text in security policy: .github/security.md:1
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: license-cc0:0
- Info: FSF or OSI recognized license: Creative Commons Zero v1.0 Universal: license-cc0:0
Reason
Found 19/30 approved changesets -- score normalized to 6
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Warn: no topLevel permission defined: .github/workflows/ts-canary.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/type-fest/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/type-fest/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:43: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/type-fest/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:44: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/type-fest/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ts-canary.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/type-fest/ts-canary.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ts-canary.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/type-fest/ts-canary.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:28
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:48
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:49
- Warn: npmCommand not pinned by hash: .github/workflows/ts-canary.yml:23
- Warn: npmCommand not pinned by hash: .github/workflows/ts-canary.yml:24
- Info: 0 out of 6 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 5 npmCommand dependencies pinned
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 19 are checked with a SAST tool
Score
5.6
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More