子宫内膜炎吃什么药| 嘴臭是什么原因| 儿童咳嗽挂什么科| 甲状腺结节吃什么水果好| 神经紊乱会出现什么症状| 明年属什么生肖| 三伏贴什么时候贴| 榴莲不可以和什么食物一起吃| 破关是什么意思| 梦见青蛙是什么意思| 脚心烧是什么原因| 喉咙看什么科| 益生菌什么牌子好| 鹦鹉吃什么食物最好| 虾滑是什么| 血糖高一日三餐吃什么东西最适合| 驾驶证和行驶证有什么区别| 龙的幸运色是什么颜色| 对食什么意思| 双绿生肖是什么生肖| 李白属什么生肖的| 去脚气用什么药最好| 什么人不穿衣服| 吃什么补充维生素c| 孕妇拉肚子是什么原因引起的| 套牌车是什么意思| 4月15号是什么星座| 县团委书记是什么级别| 头晕恶心呕吐是什么原因| 腰疼吃什么药最有效| 电压mv是什么意思| 孕期应该吃什么| 地球上什么东西每天要走的距离最远| 左眼跳是什么意思| 白带多是什么原因引起的| 吃什么调理卵巢早衰| 鹿角有什么功效和作用| 农历十月初八是什么星座| 打哈欠为什么会传染| mn是什么单位| 检查宫颈做什么检查| 儿童办护照需要什么证件| 局部皮肤瘙痒什么原因| 什么然不同| 红枣为什么要炒黑再泡水喝| 什么是性高潮| 胆囊壁胆固醇结晶是什么意思| 关帝庙求什么最灵| 被舔是什么感觉| 对虾是什么虾| 硬卧是什么样子的| 君子兰有什么特点| 7月17日什么星座| 芦根煮水的功效是什么| 血沉高忌口什么| 四川属于什么气候| 1月2日什么星座| 蚊子怕什么颜色| 诸葛亮为什么气死周瑜| 风花雪月什么意思| 甲方是什么意思| 月光石五行属什么| 头疼应该挂什么科| 卡针是什么| 拔罐的原理是什么| 1931年属相是什么| 北京的市花是什么| 屎是什么味道| 一个虫一个离念什么| 六味地黄丸吃多了有什么副作用| 不孕不育都检查什么项目| 痔疮便血吃什么药| 男人说做朋友代表什么| 冬至为什么吃饺子| 全身体检挂什么科| 梦见钱包丢了是什么意思| 女性湿气重喝什么茶| 气短心悸是什么意思| 唾液是什么| 左眼跳财是什么意思| dm是什么| 插科打诨是什么意思| 小孩指甲有白点是什么原因| 11月30号是什么星座| 西安有什么区| 舌根放血有什么好处| 乳头痛是什么征兆| 射精什么意思| 精尽人亡什么意思| 法院院长是什么级别| 为什么不能空腹喝豆浆| 孙俪最新电视剧叫什么| 用什么泡脚能减肥| 桑葚是什么季节的| 肚脐眼位置疼是什么原因| 额头长痘是什么原因| 静待佳音什么意思| 馕是什么意思| 舌头热灼是什么原因| 瞎子吃核桃砸了手是什么生肖| 贫血做什么检查| 营卫不和吃什么中成药| 今晚吃什么| 梦见被警察抓预示什么| 阁字五行属什么| 渣男最怕什么样的女人| 炎细胞是什么意思| 后背中心疼是什么原因| 茯苓生长在什么地方| 拉不出大便吃什么药| 湿疹吃什么中药| 上海最高楼叫什么大厦有多少米高| 核桃壳有什么用处| 吃什么能治脂肪肝| 女娲用什么补天| 什么是热辐射| 带状疱疹后遗神经痛用什么药| 子痫前期是什么意思| 西红柿吃多了有什么坏处| 清炖排骨放什么调料| 马吃什么食物| 塌腰是什么意思| 24D是什么激素| 黄茶适合什么人喝| 皈依什么意思| 乔迁新居送什么礼物| 婚煞是什么意思| 缺失是什么意思| 上半身皮肤痒什么原因| 红绿色盲是什么遗传病| 12月是什么月| 汉菜不能和什么一起吃| 什么东西护肝养肝| 什么是龙抬头| 肾盂是什么意思| 胡汉三回来了什么意思| 什么的积雪| 用什么泡脚去湿气寒气| vcr是什么| 房间消毒杀菌用什么好| 人体最大的器官是什么| 电解质水是什么| 多汗症是什么原因引起的| 猥琐男是什么意思| 3475是什么罩杯| 鼻子干燥用什么药| 湿疹吃什么中成药| 为什么前壁容易生男孩| 算什么男人歌词| 知恩图报是什么意思| 子宫内膜手术后需要注意什么| 盲袋是什么| vgr100是什么药| 黑灰色是什么颜色| 毛囊炎是什么症状| 小病不治下一句是什么| 散光是什么意思| 晚上睡不着觉是什么原因| 月经量多是什么原因引起的| 什么玉最好有灵性养人| 十一月五号是什么星座| 打呼噜的原因是什么| 小腿肿看什么科| 大便干燥一粒一粒的吃什么药| 为什么怀不上孕| 六月二十日是什么日子| 中规中矩是什么意思| 传奇是什么意思| 三角梅用什么肥料最好| 埋怨是什么意思| 肛门痒挂什么科| 救济的近义词是什么| 纨绔子弟是什么意思| 脑膜炎是什么原因引起的| 梦见玻璃碎了什么意思| 嗓子不舒服挂什么科| 什么原因导致阴虚| 生殖细胞瘤是什么病| 维生素b补什么| penguins是什么意思| 贵州有什么好玩的| lga肾病是什么意思| 解离是什么意思| 排便困难拉不出来是什么原因| 三联和四联有什么区别| 晚八点是什么时辰| 外阴是指什么部位| 新陈代谢慢吃什么药| 什么光| 什么是脑中风| 什么日什么秋| 马躺下睡觉为什么会死| 化学专业学什么| 铁锈红配什么颜色好看| 黑色车牌是什么车| 旭五行属什么| 省委组织部部长什么级别| 白莲花什么意思| 为什么叫韩国人棒子| 补牙用什么材料最好| 女性检查甲功是什么病| 后嗣是什么意思| 金枝玉叶什么生肖| 梦见去看病是什么意思| 87年的兔是什么命| 绿五行属什么| 玄关是什么| vj是什么意思| 精索静脉曲张挂什么科| 山根有痣代表什么| 手抽筋吃什么药| 6朵玫瑰代表什么意思| 大便干燥用什么药| 4月11号是什么星座| 熬是什么意思| 抑郁症有什么症状| 福星高照是什么生肖| 一枚什么| 劲仔小鱼是什么鱼做的| 查血糖血脂挂什么科| 过三关 是什么意思| 泡脚用什么泡最好| 小本创业做什么生意好| 解酒喝什么饮料| 小腹疼痛是什么原因| 4.28是什么星座| 脑供血不足吃什么药好得快| 檀郎是什么意思| 老上火是什么原因造成的| 天德月德是什么意思| 孕妇吃什么蔬菜好| 肠道感染吃什么消炎药| 左眼跳女人是什么预兆| 吃豆腐什么意思| 轮状病毒是什么症状| 女性肾虚是什么原因导致的| 唐筛和无创有什么区别| 身上长了好多红痣是什么原因| 中度脂肪肝吃什么药| 什么鞋油好用| 如何知道自己是什么星座| 又双叒叕念什么啥意思| 附件炎是什么| 往返是什么意思| 蔻驰和古驰有什么区别| 邹的左边读什么| 做梦梦见剪头发是什么意思| 内分泌失调是什么| tin是什么| 生蚝吃多了有什么危害| 颜控什么意思| 踏青是什么意思| 卡布奇诺是什么意思| 男人吃什么补肾壮阳效果最好| 高回声是什么意思| 秃噜皮是什么意思| 茉莉茶叶有什么功效和作用| 围度什么意思| 警备区是干什么的| 胃痛怎么办吃什么药| 松香是什么| 什么人不建议吃海参| 中央委员是什么级别| 虾滑可以做什么菜| 百度
Skip to content

A collection of essential TypeScript types

License

CC0-1.0, MIT licenses found

Licenses found

CC0-1.0
license-cc0
MIT
license-mit
Notifications You must be signed in to change notification settings

sindresorhus/type-fest



npm dependents npm downloads

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

npm install type-fest

Requires TypeScript >=5.8, ESM, and {strict: true} in your tsconfig.

Note

This readme shows the current development version. For docs about the latest version, see the npm page.

Usage

import type {Except} from 'type-fest';

type Foo = {
	unicorn: string;
	rainbow: boolean;
};

type FooWithoutRainbow = Except<Foo, 'rainbow'>;
//=> {unicorn: string}

API

Click the type names for complete docs.

Basic

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 with unknown value. You probably want this instead of {}.
  • UnknownArray - Represents an array with unknown value.
  • UnknownMap - Represents a map with unknown key and value.
  • UnknownSet - Represents a set with unknown value.
  • Except - Create a type from an object type without certain keys. This is a stricter version of Omit.
  • Writable - Create a type that strips readonly from the given type. Inverse of Readonly<T>.
  • WritableDeep - Create a deeply mutable version of an object/ReadonlyMap/ReadonlySet/ReadonlyArray type. The inverse of ReadonlyDeep<T>. Use Writable<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 to Merge, 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. Use Required<T> if you only need one level deep.
  • PickDeep - Pick properties from a deeply-nested object. Use Pick<T> if you only need one level deep.
  • OmitDeep - Omit properties from a deeply-nested object. Use Omit<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. Use Partial<T> if you only need one level deep.
  • PartialOnUndefinedDeep - Create a deep version of another type where all keys accepting undefined type are set to optional.
  • UndefinedOnPartialDeep - Create a deep version of another type where all optional keys are set to also accept undefined.
  • ReadonlyDeep - Create a deeply immutable version of an object/Map/Set/Array type. Use Readonly<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 previous Opaque type, which is now deprecated.)
  • UnwrapTagged - Get the untagged portion of a tagged type created with Tagged. (This replaces the previous UnwrapOpaque 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.
  • SetRequiredDeep - Like SetRequired except it selects the keys deeply.
  • SetNonNullable - Create a type that makes the given keys non-nullable.
  • SetNonNullableDeep - Create a type that makes the specified keys non-nullable (removes null and undefined), supports deeply nested key paths, and leaves all other keys unchanged.
  • 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 given Condition type.
  • ConditionalPick - Like Pick except it selects properties from a shape where the values extend the given Condition type.
  • ConditionalPickDeep - Like ConditionalPick except that it selects the properties deeply.
  • ConditionalExcept - Like Omit except it removes properties from a shape where the values extend the given Condition type.
  • UnionToIntersection - Convert a union type to an intersection type.
  • LiteralToPrimitive - Convert a literal type to the primitive type it belongs to.
  • LiteralToPrimitiveDeep - Like LiteralToPrimitive except it converts literal types inside an object or array deeply.
  • Stringified - Create a type with the keys of the given type changed to string type.
  • IterableElement - Get the element type of an Iterable/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.
  • KeyAsString - 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 a true/false type depending on whether the given type has any optional fields.
  • RequiredKeysOf - Extract all required keys from the given type.
  • HasRequiredKeys - Create a true/false type depending on whether the given type has any required fields.
  • ReadonlyKeysOf - Extract all readonly keys from the given type.
  • HasReadonlyKeys - Create a true/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 a true/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.
  • AllExtend - Returns a boolean for whether every element in an array type extends another type.
  • NonEmptyTuple - Matches any non-empty tuple.
  • NonEmptyString - Matches any non-empty string.
  • 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.
  • ConditionalSimplify - Simplifies a type while including and/or excluding certain types from being simplified.
  • ConditionalSimplifyDeep - Recursively simplifies a type while including and/or excluding certain types from being simplified.

Type Guard

  • If - An if-else-like type that resolves depending on whether the given boolean type is true or false.
  • IsLiteral - Returns a boolean for whether the given type is a literal type.
  • IsStringLiteral - Returns a boolean for whether the given type is a string literal type.
  • IsNumericLiteral - Returns a boolean for whether the given type is a number or bigint literal type.
  • IsBooleanLiteral - Returns a boolean for whether the given type is a true or false literal type.
  • IsSymbolLiteral - Returns a boolean for whether the given type is a symbol literal type.
  • IsAny - Returns a boolean for whether the given type is any.
  • IsNever - Returns a boolean for whether the given type is never.
  • IsUnknown - Returns a boolean for whether the given type is unknown.
  • IsEmptyObject - Returns a boolean for whether the type is strictly equal to an empty plain object, the {} value.
  • IsNull - Returns a boolean for whether the given type is null.
  • IsTuple - Returns a boolean for whether the given array is a tuple.
  • IsUnion - Returns a boolean for whether the given type is a union.
  • IsLowercase - Returns a boolean for whether the given string literal is lowercase.
  • IsUppercase - Returns a boolean for whether the given string literal is uppercase.
  • IsOptional - Returns a boolean for whether the given type includes undefined.
  • IsNullable - Returns a boolean for whether the given type includes null.

JSON

  • Jsonify - Transform a type to one that is assignable to the JsonValue 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

Async

  • Promisable - Create a type that represents either the value or the value wrapped in PromiseLike.
  • AsyncReturnType - Unwrap the return type of a function that returns a Promise.
  • 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 like String#slice().
  • StringRepeat - Returns a new string which contains the specified number of copies of a given string, just like String#repeat().
  • RemovePrefix - Removes the specified prefix from the start of a string.

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 like Array#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.

Numeric

  • PositiveInfinity - Matches the hidden Infinity type.
  • NegativeInfinity - Matches the hidden -Infinity type.
  • Finite - A finite number.
  • Integer - A number that is an integer.
  • Float - A number that is not an integer.
  • NegativeFloat - A negative (-∞ < x < 0) number that is not an integer.
  • Negative - A negative number/bigint (-∞ < x < 0)
  • NonNegative - A non-negative number/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, like 1.5 or -1.5.
  • IsInteger - Returns a boolean for whether the given number is a integer, like -5, 1.0 or 100.
  • 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

Miscellaneous

Improved built-in

  • ExtendsStrict - A stricter, non-distributive version of extends for checking whether one type is assignable to another.
  • ExtractStrict - A stricter version of Extract<T, U> that ensures every member of U can successfully extract something from T.
  • ExcludeStrict - A stricter version of Exclude<T, U> that ensures every member of U can successfully exclude something from T.

Declined types

If we decline a type addition, we will make sure to document the better solution here.

  • Diff and Spread - 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> vs Record<string, number>) from Record, which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We have Map in JavaScript now.
  • ExtractProperties and ExtractMethods - 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 from null.
  • TitleCase - It's not solving a common need and is a better fit for a separate package.
  • ExtendOr and ExtendAnd - The benefits don't outweigh having to learn what they mean.
  • PackageJsonExtras - There are too many possible configurations that can be put into package.json. If you would like to extend PackageJson 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.

Tips

Extending existing types

  • PackageJson - There are a lot of tools that place extra configurations inside the package.json file. You can extend PackageJson to support these additional configurations.

    Example

    Playground

     import type {PackageJson as BasePackageJson} from 'type-fest';
     import type {Linter} from 'eslint';
    
     type PackageJson = BasePackageJson & {eslintConfig?: Linter.Config};

Related

Built-in types

There are many advanced types most users don't know about.

  • Awaited<T> - Extract the type of a value that a Promise resolves to.

    Example

    Playground

    interface User {
    	id: number;
    	name: string;
    	age: number;
    }
    
    class UserApiService {
    	async fetchUser(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
    		};
    	}
    }
    
    type FetchedUser = Awaited<ReturnType<UserApiService['fetchUser']>>;
    
    async function handleUserData(apiService: UserApiService, userId: number) {
    	try {
    		const user: FetchedUser = await apiService.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
    	}
    }
    
    const userApiService = new UserApiService();
    handleUserData(userApiService, 1);
  • Partial<T> - Make all properties in T optional.

    Example

    Playground

     interface NodeConfig {
     		appName: string;
     		port: number;
     }
    
     class NodeAppBuilder {
     		private configuration: NodeConfig = {
     				appName: 'NodeApp',
     				port: 3000
     		};
    
     		private updateConfig<Key extends keyof NodeConfig>(key: Key, value: NodeConfig[Key]) {
     				this.configuration[key] = value;
     		}
    
     		config(config: Partial<NodeConfig>) {
     				type NodeConfigKey = keyof NodeConfig;
    
     				for (const key of Object.keys(config) as NodeConfigKey[]) {
     						const updateValue = config[key];
    
     						if (updateValue === undefined) {
     								continue;
     						}
    
     						this.updateConfig(key, updateValue);
     				}
    
     				return this;
     		}
     }
    
     // `Partial<NodeConfig>`` allows us to provide only a part of the
     // NodeConfig interface.
     new NodeAppBuilder().config({appName: 'ToDoApp'});
  • Required<T> - Make all properties in T required.

    Example

    Playground

     interface ContactForm {
     		email?: string;
     		message?: string;
     }
    
     function submitContactForm(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 in T readonly.

    Example

    Playground

     enum LogLevel {
     		Off,
     		Debug,
     		Error,
     		Fatal
     };
    
     interface LoggerConfig {
     		name: string;
     		level: LogLevel;
     }
    
     class Logger {
     		config: Readonly<LoggerConfig>;
    
     		constructor({name, level}: LoggerConfig) {
     				this.config = {name, level};
     				Object.freeze(this.config);
     		}
     }
    
     const config: LoggerConfig = {
     	name: 'MyApp',
     	level: LogLevel.Debug
     };
    
     const logger = new Logger(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> - From T, pick a set of properties whose keys are in the union K.

    Example

    Playground

     interface Article {
     		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}`
     type ArticlePreview = Pick<Article, 'title' | 'thumbnail'>;
    
     // Render a list of articles using only title and description.
     function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement {
     		const articles = document.createElement('div');
    
     		for (const preview of previews) {
     				// Append preview to the articles.
     		}
    
     		return articles;
     }
    
     const articles = renderArticlePreviews([
     		{
     			title: 'TypeScript tutorial!',
     			thumbnail: '/assets/ts.jpg'
     		}
     ]);
  • Record<K, T> - Construct a type with a set of properties K of type T.

    Example

    Playground

     // Positions of employees in our company.
     type MemberPosition = 'intern' | 'developer' | 'tech-lead';
    
     // Interface describing properties of a single employee.
     interface Employee {
     		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.
     const team: 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 missing
     const teamEmpty: Record<MemberPosition, null> = {
     		intern: null,
     		developer: null,
     };
  • Exclude<T, U> - Exclude from T those types that are assignable to U.

    Example

    Playground

     interface ServerConfig {
     	port: null | string | number;
     }
    
     type RequestHandler = (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.
     function getPortValue(port: Exclude<ServerConfig['port'], null>): number {
     	if (typeof port === 'string') {
     		return parseInt(port, 10);
     	}
    
     	return port;
     }
    
     function startServer(handler: RequestHandler, config: ServerConfig): void {
     	const server = require('http').createServer(handler);
    
     	const port = config.port === null ? 3000 : getPortValue(config.port);
     	server.listen(port);
     }
  • Extract<T, U> - Extract from T those types that are assignable to U.

    Example

    Playground

     declare function uniqueId(): number;
    
     const ID = Symbol('ID');
    
     interface Person {
     	[ID]: number;
     	name: string;
     	age: number;
     }
    
     // Allows changing the person data as long as the property key is of string type.
     function changePersonData<
     	Obj extends Person,
     	Key extends Extract<keyof Person, string>,
     	Value extends Obj[Key]
     > (obj: Obj, key: Key, value: Value): void {
     	obj[key] = value;
     }
    
     // Tiny Andrew was born.
     const andrew = {
     	[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> - Exclude null and undefined from T.

    Example Works with strictNullChecks set to true.

    Playground

     type PortNumber = string | number | null;
    
     /** Part of a class definition that is used to build a server */
     class ServerBuilder {
     		portNumber!: NonNullable<PortNumber>;
    
     		port(this: ServerBuilder, port: PortNumber): ServerBuilder {
     				if (port == null) {
     						this.portNumber = 8000;
     				} else {
     						this.portNumber = port;
     				}
    
     				return this;
     		}
     }
    
     const serverBuilder = new ServerBuilder();
    
     serverBuilder
     		.port('8000')   // portNumber = '8000'
     		.port(null)     // portNumber =  8000
     		.port(3000);    // portNumber =  3000
    
     // TypeScript error
     serverBuilder.portNumber = null;
  • Parameters<T> - Obtain the parameters of a function type in a tuple.

    Example

    Playground

     function shuffle(input: any[]): void {
     	// Mutate array randomly changing its' elements indexes.
     }
    
     function callNTimes<Fn extends (...arguments_: any[]) => any> (func: Fn, callCount: number) {
     	// Type that represents the type of the received function parameters.
     	type FunctionParameters = Parameters<Fn>;
    
     	return function (...arguments_: FunctionParameters) {
     		for (let i = 0; i < callCount; i++) {
     			func(...arguments_);
     		}
     	}
     }
    
     const shuffleTwice = callNTimes(shuffle, 2);
  • ConstructorParameters<T> - Obtain the parameters of a constructor function type in a tuple.

    Example

    Playground

     class ArticleModel {
     	title: string;
     	content?: string;
    
     	constructor(title: string) {
     		this.title = title;
     	}
     }
    
     class InstanceCache<T extends (new (...arguments_: any[]) => any)> {
     	private ClassConstructor: T;
     	private cache: Map<string, InstanceType<T>> = new Map();
    
     	constructor (ctr: T) {
     		this.ClassConstructor = ctr;
     	}
    
     	getInstance (...arguments_: ConstructorParameters<T>): InstanceType<T> {
     		const hash = this.calculateArgumentsHash(...arguments_);
    
     		const existingInstance = this.cache.get(hash);
     		if (existingInstance !== undefined) {
     			return existingInstance;
     		}
    
     		return new this.ClassConstructor(...arguments_);
     	}
    
     	private calculateArgumentsHash(...arguments_: any[]): string {
     		// Calculate hash.
     		return 'hash';
     	}
     }
    
     const articleCache = new InstanceCache(ArticleModel);
     const amazonArticle = articleCache.getInstance('Amazon forests burning!');
  • ReturnType<T> - Obtain the return type of a function type.

    Example

    Playground

     /** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */
     function mapIter<
     		Elem,
     		Func extends (elem: Elem) => any,
     		Ret extends ReturnType<Func>
     >(iter: Iterable<Elem>, callback: Func): Ret[] {
     		const mapped: Ret[] = [];
    
     		for (const elem of iter) {
     				mapped.push(callback(elem));
     		}
    
     		return mapped;
     }
    
     const setObject: Set<string> = new Set();
     const mapObject: Map<number, string> = new Map();
    
     mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[]
    
     mapIter(mapObject, ([key, value]: [number, string]) => {
     		return key % 2 === 0 ? value : 'Odd';
     }); // string[]
  • InstanceType<T> - Obtain the instance type of a constructor function type.

    Example

    Playground

     class IdleService {
     		doNothing (): void {}
     }
    
     class News {
     		title: string;
     		content: string;
    
     		constructor(title: string, content: string) {
     				this.title = title;
     				this.content = content;
     		}
     }
    
     const instanceCounter: Map<Function, number> = new Map();
    
     interface Constructor {
     		new(...arguments_: any[]): any;
     }
    
     // Keep track how many instances of `Constr` constructor have been created.
     function getInstance<
     		Constr extends Constructor,
     		Arguments extends ConstructorParameters<Constr>
     >(constructor: Constr, ...arguments_: Arguments): InstanceType<Constr> {
     		let count = instanceCounter.get(constructor) || 0;
    
     		const instance = new constructor(...arguments_);
    
     		instanceCounter.set(constructor, count + 1);
    
     		console.log(`Created ${count + 1} instances of ${Constr.name} class`);
    
     		return instance;
     }
    
    
     const idleService = getInstance(IdleService);
     // Will log: `Created 1 instances of IdleService class`
     const newsEntry = 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

    Playground

     interface Animal {
     		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.
     type AnimalShortInfo = Omit<Animal, 'images' | 'paragraphs'>;
    
     function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement {
     		const container = document.createElement('div');
     		// Internal implementation.
     		return container;
     }
  • Uppercase<S extends string> - Transforms every character in a string into uppercase.

    Example
     type T = Uppercase<'hello'>;  // 'HELLO'
    
     type T2 = Uppercase<'foo' | 'bar'>;  // 'FOO' | 'BAR'
    
     type T3<S extends string> = Uppercase<`aB${S}`>;
     type T4 = T3<'xYz'>;  // 'ABXYZ'
    
     type T5 = Uppercase<string>;  // string
     type T6 = Uppercase<any>;  // any
     type T7 = Uppercase<never>;  // never
     type 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
     type T = Lowercase<'HELLO'>;  // 'hello'
    
     type T2 = Lowercase<'FOO' | 'BAR'>;  // 'foo' | 'bar'
    
     type T3<S extends string> = Lowercase<`aB${S}`>;
     type T4 = T3<'xYz'>;  // 'abxyz'
    
     type T5 = Lowercase<string>;  // string
     type T6 = Lowercase<any>;  // any
     type T7 = Lowercase<never>;  // never
     type 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
     type T = Capitalize<'hello'>;  // 'Hello'
    
     type T2 = Capitalize<'foo' | 'bar'>;  // 'Foo' | 'Bar'
    
     type T3<S extends string> = Capitalize<`aB${S}`>;
     type T4 = T3<'xYz'>;  // 'ABxYz'
    
     type T5 = Capitalize<string>;  // string
     type T6 = Capitalize<any>;  // any
     type T7 = Capitalize<never>;  // never
     type 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
     type T = Uncapitalize<'Hello'>;  // 'hello'
    
     type T2 = Uncapitalize<'Foo' | 'Bar'>;  // 'foo' | 'bar'
    
     type T3<S extends string> = Uncapitalize<`AB${S}`>;
     type T4 = T3<'xYz'>;  // 'aBxYz'
    
     type T5 = Uncapitalize<string>;  // string
     type T6 = Uncapitalize<any>;  // any
     type T7 = Uncapitalize<never>;  // never
     type 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)

用盐洗头发有什么好处 何去何从是什么意思 为什么排卵期会出血 身份证照片穿什么颜色衣服 李逵代表什么生肖
胳肢窝疼痛是什么原因 大芒果是什么品种 孩子咽炎老是清嗓子吃什么药 螺子黛是什么 桑拓木命是什么意思
胆道闭锁有什么症状 注册安全工程师什么时候报名 长沙有什么区 弯刀裤适合什么人穿 树莓色是什么颜色
飞机是什么 芡实是什么 幽门螺杆菌有什么症状 先知是什么意思 为什么要多吃鱼
单脐动脉是什么意思hcv8jop2ns4r.cn 大陆人去香港需要什么证件hcv8jop9ns1r.cn 朱砂有什么作用与功效hcv7jop9ns9r.cn 什么是生理盐水hcv7jop9ns2r.cn 丹参有什么功效hcv8jop2ns2r.cn
下压高是什么原因引起的hcv7jop6ns4r.cn 怀孕送什么礼物baiqunet.com 三伏天是什么时候开始hcv8jop5ns2r.cn 卵泡不破是什么原因hcv8jop9ns4r.cn 媛交是什么意思hcv7jop7ns2r.cn
梦见老公有外遇预示什么hcv9jop1ns4r.cn 花子是什么意思hcv9jop5ns7r.cn 粉籍是什么意思hcv8jop2ns3r.cn 狗狗流眼泪是什么原因hcv7jop9ns6r.cn 92年是什么命hcv8jop2ns1r.cn
子宫内膜不典型增生是什么意思hcv9jop4ns6r.cn 夏季喝什么茶好hcv9jop3ns1r.cn 对策是什么意思jasonfriends.com 吃什么降尿酸最有效食物520myf.com 豆瓣是什么软件hcv8jop0ns7r.cn
百度