Intrinsic Types in TypeScript

Even though the notion of intrinsic types might baffle the reader, I will not define them right away, as I want to introduce the concept using a practical example. I would love to start the article with the following question, something I have asked myself in various forms over the years:

In an ideal, statically-typed language, how could one define the string capitalisation type, using the properties of its type system?

I could substitute string capitalisation with string permutation and the issue still remains valid, as long as it touches not the abstraction of types, but their intrinsic properties.

Solving the Assignment

The way I wrote the aforementioned assignment grants a lot of freedom in regards to choosing the utilised type system. However, one must recognise implicit requirements for certain features, like generics, string literals or inheritance. Since ordered lists of characters make strings, the question “which encoding applies to characters?” requires an instant answer.

I would name the type CapitalizedString and define it as a parametrised type (or a generic type, depends on the domain language of the chosen type system) with the single parameter T constrained to a string literal type. All characters in strings should adhere to the UTF-8 encoding. One could write it down easily using pseudocode in the following fashion:

type CapitalizedString<T extends string literal> = ...

By definition, if the string literal in question has no characters, the operation has obviously no effect on it. Otherwise, capitalisation alters only the first character of the string in question, leaving the rest unchanged. To uppercase a character, the type system needs to support it ad hoc, as defining it explicitly in the type system sounds impractical for UTF-8 characters due to complexity of such an algorithm (I find it inadvisable even for ASCII characters).

Therefore, the compiler itself must provide implementation of uppercasing any UTF-8 character, making the uppercase operation an ad hoc, or rather an intrinsic property of the type system. There exist multiple ways of declaring such a property in type definitions, for example:

intrinsic type Uppercase<T extends character>; 
type Uppercase<T extends character> = intrinsic;

An avid reader might note that the aforewritten definitions provide no return type explicitly — since the compiler performs the operation, nobody knows the return type beforehand. The type system might define uppercasing as an unary operator, accepting a single character, as shown in the following snippet:

type UppercaseA = uppercase 'a';

In the end, the CapitalisedString type boils down to the following definition:

type CapitalisedString<T extends string literal> =
    T === '' ? '' : Uppercase<T[0]> + T[1...];

In order for the definition to work, the type system in question requires:

  • an ability for equality comparison of two string literal types,
  • a possibility to access both the n-th character and a range of characters of any string literal type,
  • permission to use conditional statements in type definitions.

#javascript #typescript #type-systems

What is GEEK

Buddha Community

Intrinsic Types in TypeScript

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource 

Verdie  Murray

Verdie Murray

1636240140

What Is The Main Difference Of TYPES Vs INTERFACES in TypeScript

TypeScript has two ways of declaring structures of your objects in the form of  #types (type aliases) and #interfaces.

In this lesson we will look at the technical differences between these two, when you should use which, along with real world #TypeScript code analysis, and community thoughts

#typescript 

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Christa  Stehr

Christa Stehr

1599315360

Nominal typing in Typescript

Nominal & structural typing

Type systems are typically categorized as either structural or nominal. Languages like Java and Scala have primarily nominal type systems, whereas a language like Typescript has a structural type system. Let’s take a brief look at both systems.

Nominal Typing

In a nominal typing system, type compatibility is checked using the name of the types. If they do not have the same name, then they are not compatible; end of story. **If **Typescript had a nominal typing system the type check for the last line would fail:

Image for post

Structural typing

Typescript uses structural typing to decide whether two types are compatible with one another or not. What do we mean by structural typing? Well, let’s consider the following code snippet:

Image for post

To determine whether the type of the constant color(RGBA) is compatible with the type of serializeColor’s parameter x(RGB) the type system must verify that each member of RGB has a corresponding compatible member in RGBA. In this case, RGB has a single member color for which RGBA has a corresponding member with the same type — [number, number, number] — and so it passes the type check. Notice how the type system ignores the additional members that exist on RGBA (alpha).

#typescript #type-safe #type-systems

Type-plus: Additional Types & Types Adjusted Utilities for TypeScript

type-plus

Provides additional types and type adjusted utilities for TypeScript.

Feature Highlights

Installation

npm install type-plus
// or
yarn add type-plus

Type Assertions

Type assertion is one of the main features of type-plus.

There are 5 kinds of type assertions:

  • runtime: validates during runtime.
  • immediate: validates at compile time.
  • type guard: User-defined type guard functions (if (isBool(s))) introduced in TypeScript 1.6.
  • assertion function: assertion functions (assertIsBool(a)) introduced in TypeScript 3.7.
  • logical: functions or generic types that returns true or false type to be used in type level programming.
  • filter: generic types that returns never if the test fails.

Here are the type assertions provided in type-plus. Use the one that fits your specific needs.

assertType<T>(subject):

✔️ immediate

It ensures subject satisfies T. It is similar to const x: T = subject without introducing an unused variable. You need to specify T for it to work.

assertType<T>(subject, validator):

assertType<T>(subject, Class):

✔️ assertion function, runtime

These overloads of assertType allow you to specify a validator. With these overloads, subject can be unknown or any.

If subject fails the assertion, a standard TypeError will be thrown and provide better error info. For example:

const s: unknown = 1

// TypeError: subject fails to satisfy s => typeof s === 'boolean'
assertType<boolean>(s, s => typeof s === 'boolean')

The message beautification is provided by tersify.

assertType.isUndefined(subject):

assertType.isNull(subject):

assertType.isNumber(subject):

assertType.isBoolean(subject):

assertType.isTrue(subject):

assertType.isFalse(subject):

assertType.isString(subject):

assertType.isFunction(subject):

assertType.isConstructor(subject):

assertType.isError(subject):

✔️ immediate, assertion function, runtime

Compiler and runtime assertion with type narrowing from any. They assert the type of subject is that specific type. i.e. union type will fail at type level:

const s: number | undefined = undefined
assertType.isUndefined(s) // TypeScript complains

They accept any and will be narrowed to the specific type.

const s: any = undefined
assertType.isUndefined(s)
s // type is undefined

assertType.isNever(subject):

✔️ immediate

Check if the subject type is never. This function is not very useful in actual code as TypeScript will indicate the error. But it can be useful when writing tests for types.

This is useful for variables. For type level only check, do the following:

assertType.isTrue(true as Equal<YourType, never>)

assertType.noUndefined(subject):

assertType.noNull(subject):

assertType.noNumber(subject):

assertType.noBoolean(subject):

assertType.noTrue(subject):

assertType.noFalse(subject):

assertType.noString(subject):

assertType.noFunction(subject):

assertType.noError(subject):

✔️ immediate, runtime

Compiler and runtime assertion. Assert subject type does not contain the specific type. Work against unions.

const s: number | undefined = 1
assertType.noUndefined(s) // TypeScript complains

They accept subject with type any or unknown, the assertion will happen in runtime to ensure subject is the specific type.

isType<T>(subject: T):

✔️ immediate

It ensures subject satisfies T. It is identical to assertType<T>(subject: T). You need to specify T.

isType<T>(subject, validator):

isType<T>(subject, Class):

isType.t<T>(subject?: T):

✔️ immediate, runtime

It can used as type check: isType.t<Equal<A, B>>(), or value type check: isType.t(valueTypeIsTrue). It returns true when passes (which is the only case when used in TypeScript).

isType.f<T>(subject?: T):

✔️ immediate, runtime

It can used as type check: isType.f<Equal<A, B>>(), or value type check: isType.f(valueTypeIsFalse). It returns true when passes (which is the only case when used in TypeScript).

isType.equal<true|false, A, B>():

✔️ immediate

Slightly easier to use then isType.t<>() and isType.f<>(), when doing type-level only equality comparison as you don't have to import Equal<>.

✔️ type guard, runtime

These overloads of isType allow you to specify a validator. With these overloads, subject can be unknown or any.

Equal<A, B>: IsEqual<A, B>:

✔️ logical

Check if A and B are the same.

NotEqual<A, B>: IsNotEqual<A, B>:

✔️ logical

Check if A and B are not the same.

IsExtend<A, B>: IsNotExtend<A, B>:

✔️ logical

Check if A extends or not extends B.

Extendable<A, B>: NotExtendable<A, B>:

✔️ filter

Check if A extends or not extends B.

IsAssign<A, B>: CanAssign<A, B>:

✔️ logical

Check if A can be assigned to B. A typical usage is using it with assertType:

assertType.isFalse(false as CanAssign<boolean, { a: string }>)
assertType.isTrue(true as CanAssign<{ a:string, b:number }, { a: string }>)

canAssign<T>(): (subject) => true:

✔️ immediate, logical

Returns a compile-time validating function to ensure subject is assignable to T.

const isConfig = canAssign<{ a: string }>()
assertType.isTrue(isConfig({ a: 'a' }))

canAssign<T>(false): (subject) => false:

✔️ immediate, logical

Returns a compile-time validating function to ensure subject is not assignable to T.

const notA = canAssign<{ a: string }>(false)
assertType.isTrue(notA({ a: 1 }))

notA({ a: '' }) // TypeScript complains

Type Utilities

type-plus also provides additional type utilities. These utilities include utility types and type-adjusted functions.

Note that most predicate types (such as IsAny<>) have a Then and Else that you can override.

e.g.:

type Yes = IsAny<any, 'yes', 'no'> // 'yes'
type No = IsAny<1, 'yes', 'no'> // 'no'

Array function

  • CommonPropKeys<A>: gets common keys inside the records in the array A (deprecate CommonKeys).
  • Concat<A, B>: [...A, ...B].
  • CreateTuple<L, T>: Creates Tuple<T> with L number of elements.
  • DropFirst<A>: drops the first value type of A.
  • DropLast<A>: drops the last value type of A.
  • Filter<A, Criteria>: gets the array of types satisfying Criteria in A.
  • FindFirst<A, Criteria>: gets the first type satisfying Criteria.
  • FindLast<A, Criteria>: gets the last type satisfying Criteria.
  • Head<A>: gets the first entry in the array.
  • IntersectOfProps<A, K>: gets the intersect of A[K] types (deprecate MapToProp)
  • IsArray<T>: logical predicate for Array.
  • Last<A>: gets the last type of an array or tuple.
  • literalArray(...entries): return an array whose items are restricted to the provided literals.
  • PadLeft<A, Total, PadWith>: pads A with PadWith if the length of A is less than L.
  • reduceWhile(): reduce() with predicate for early termination. 
    A simple version of the same function in the ramda package.
  • Reverse<A>: reverses the order of A.
  • Some<A, Criteria>: true if some elements in A matches Criteria.
  • Tail<A>: Gets the types of a tuple except the first entry.
  • UnionOfProps<A, K>: gets the union of A[K] types (deprecate PropUnion).
  • UnionOfValues<A>: gets the union of value types in A (deprecate ArrayValue).

Constant Types

  • KeyTypes: type of all keys.
  • PrimitiveTypes: all primitive types, including Function, symbol, and bigint.
  • ComposableTypes: Types that can contain custom properties. i.e. object, array, function.
  • NonComposableTypes: Types that cannot contain custom properties. i.e. not composable.

JSON Support

  • JSONPrimitive: primitive types valid in JSON
  • JSONObject: JSON object
  • JSONArray: JSON array
  • JSONTypes: all JSON compatible types.
  • JSONTypes.get<T>(obj, ...props): get a cast value in json
import { JSONTypes } from 'type-plus'

const someJson: JSONTypes = { a: { b: ['z', { c: 'miku' }]}}

JSONTypes.get<string>(someJson, 'a', 'b', 1, 'c') // miku

Object Key functions

  • filterKey(): type adjusted filter by key.
  • findKey(): type adjusted find by key.
  • forEachKey(): type adjusted for each by key.
  • HasKey<T, K>: predicate type checking T has key K.
  • hasKey(): function of HasKey.
  • IsRecord<T>: logical predicate for Record.
  • KeysWithDiffTypes<A, B>: gets the keys common in A and B but with different value type.
  • mapKey(): type adjusted map by key.
  • reduceByKey(): type adjusted reduce by key.
  • someKey(): type adjusted some by key.
  • SpreadRecord<A, B>: type for {...a, ...b} when both a and b are Record
    for array, just do [...A, ...B].

Promise function

  • isPromise<R>(subject: any): isPromise() type guard.
  • PromiseValue<P>: Gets the type within the Promise.
  • PromiseValueMerge<P1, P2, ...P9>: Merge the values of multiple promises.
  • mapSeries(): Similar to bluebird.mapSeries() but works with async/await.

Type manipulation

  • ANotB<A, B>: get object with properties in A and not in B, including properties with a different value type.
  • BNotA<A, B>: flip of ANotB
  • as<T>(subject): assert subject as T. Avoid ASI issues such as ;(x as T).abc
  • asAny(subject): assert subject as any. Avoid ASI issue such as ;(x as any).abc
  • Except<T, K>: Deprecated. Same as Omit<T, K>.
  • ExcludePropType<T, U>: excludes type U from properties in T.
  • KeyofOptional<T>: keyof that works with Record<any, any> | undefined.
  • KnownKeys<T>: extract known (defined) keys from type T.
  • LeftJoin<A, B>: left join A with B
  • Omit<T, K>: From T, pick a set of properties whose keys are not in the union K. This is the opposite of Pick<T, K>.
  • OptionalKeys<T>: gets keys of optional properties in T.
  • PartialExcept<T, U>: Deprecated. Same as PartialOmit<T, U>.
  • PartialOmit<T, U>: makes the properties not specified in U becomes optional.
  • PartialPick<T, U>: makes the properties specified in U becomes optional.
  • Pick<T, K>: pick properties K from T. Works with unions.
  • RecursivePartial<T>: make type T optional recursively.
  • RecursiveRequired<T>: make type T required recursively.
  • ReplaceProperty<T, K, V>: replace property K in T with V.
  • RequiredKeys<T>: gets keys of required properties in T.
  • RequiredPick<T, U>: makes the properties specified in U become required.
  • RequiredExcept<T, U>: makes the properties not specified in U become required.
  • RecursiveIntersect<T, U>: intersect type U onto T recursively.
  • ValueOf<T>: type of the value of the properties of T.
  • Widen<T>: widen literal types.
  • PropType: ...no helper type for this. Just do YourType['propName'].

Type Predicates

Type predicates are type alias that returns true or false. They can be used to compose complex types.

  • HasKey<T, K>: predicate type checking T has key K.
  • IsAny<T>: T === any.
  • IsBoolean<T>: check for boolean, but not for true nor false.
  • IsDisjoint<A, B>: is A and B is a disjoint set.
  • IsEmptyObject<T>: is T === {}.
  • IsLiteral<T>: is T a literal type (literal string or number).

Logical

  • If<Condition, Then = true, Else = false>: if statement.
  • And<A, B>: logical AND.
  • Or<A, B>: logical OR.
  • Xor<A, B>: logical XOR.
  • Not<X>: logical NOT.

Note that these types work correctly with the boolean type. e.g.:

  • And<boolean, true> -> boolean
  • Not<boolean> -> boolean

There is a problem with generic distribution: https://github.com/microsoft/TypeScript/issues/41053 So you may encounter some weird behavior if your logic is complex.

Math

  • Abs<N, Fail=never>: Abs(N), Abs<number> returns Fail.
  • IsPositive<N>: is N a positive number literal. IsPositive<number> returns false.
  • IsWhole<N>: is N a whole number literal. IsWhole<number> returns false.
  • Max<A, B, Fail=never>: max(A, B), for positive and whole number, Fail otherwise.
  • GreaterThan<A, B, Fail=never>: A > B for positive and whole numbers, Fail otherwise.

Arithmetics

  • Add<A, B, Fail=never>: A + B for positive and whole numbers, Fail otherwise.
  • Subtract<A, B, Fail=never>: A - B for positive and whole numbers, Fail otherwise.
  • Increment<A, Fail=never>: alias of Add<A, 1, Fail>.
  • Decrement<A, Fail=never>: alias of Subtract<A, 1, Fail>.

Utility Functions

  • facade(subject, ...props): create a facade of subject.
  • getField(subject, key, defaultValue): get a field from a subject. Works against nullable and optional subject.
  • hasKey(): function of HasKey.
  • hasProperty(value, prop): assert value has property prop. This will pick the correct union type.
  • isConstructor(subject): type guard subject is a constructor.
  • isSystemError(code, err): type guard err with Nodejs error code.
  • omit(obj, ...props): omit properties from obj.
  • pick(obj, ...props): pick properties from obj.
  • record<K, V>(value?): create a Record<K, V> without extra object prototype.
  • required(...): merge options and removing Partial<T>. From unpartial
  • requiredDeep(...): merge options deeply and removing Partial<T>. From unpartial
  • split(target, ...splitters): split one object into multiple objects.
  • stub<T>(value): stub a particular type T.
  • typeOverrideIncompatible<T>(): override only the incompatible portion between two types.
type A =  {
  foo: boolean,
  bar: string,
  baz: string
}

const overrider = typeOverrideIncompatible<A>()
const source = {
  foo: 1,
  bar: 'bar',
  baz: 'baz'
}

// only the `foo` property is available to override.
overrider(source, { foo: !!source.foo })

Nominal Types

The TypeScript type system is structural.

In some cases, we want to express a type with nominal behavior. type-plus provides two kinds of nominal types: Brand and Flavor.

Brand<B, T>:

brand(type, subject?):

Branded nominal type is the stronger nominal type of the two. It disallows unbranded type assigned to it:

const a = brand('a', { a: 1 })
const b = { a: 1 }
a = b // error

subject can be any type, from primitive to strings to objects.

brand(type):

If you do not provide subject, brand(type) will return a brand creator, so that you can use it to create multiple branded values:

const nike = brand('nike')
const shirt = nike('shirt')
const socks = nike('socks')

Flavor<F, T>:

flavor(type, subject?):

The key difference between Flavor and Brand is that unflavored type can be assigned to Flavor:

let f = flavor('orange', 'soda')
f = 'mist' // ok

Also, Brand of the same name can be assigned to Flavor, but Flavor of the same name cannot be assigned to Brand.

nominalMatch(a, b):

nominalMatch() can be used to compare Brand or Flavor.

const b1 = brand('x', 1)
const b2 = brand('y', 1)

nominalMatch(b1, b2) // false

Functional Types

  • ChainFn<T>: T: chain function that returns the input type.
  • compose(...fns): F: compose functions

Attribution

Some of the code in this library is created by other people in the TypeScript community. I merely adding them in and maybe making some adjustments. Whenever possible, I add attribution to the person who created those codes in the file.

Similar projects

  • ts-essentials, all essential TypeScript types in one place.
  • ts-toolbelt, a more mature type lib.
  • type-fest, a collection of essential TypeScript types.
  • type-zoo, a modest type lib usable today.
  • typepark, a new type collection offering tuple manipulation and Pipe.
  • typelevel-ts, a type lib by @gcanti, author of several FP libs in TS.
  • typical, a playground of type-level operations for TypeScript.

Contribute

# after fork and clone
npm install

# begin making changes
git checkout -b <branch>
npm run watch

# after making change(s)
git commit -m "<commit message>"
git push

# create PR

Author: Unional
Source Code: https://github.com/unional/type-plus 
License: MIT License

#typescript #types