const test = (person: String) => {
console.log(person)
}
test('1')
let a = 'a'
a = '1'
const b: number[] = [10, 11]
const c: Array<number> = [10, 11]
let d: any = {}
d = 1
const test2 = () => {
console.log(1)
}
const e = [1, 2, 3]
e.forEach(v => console.log(v))
const f = { x: '1', y: 2 }
const test3 = (obj: { name?: string }) => {
console.log(obj.name?.toUpperCase)
}
test3({})
test3({ name: '? -- 可以传 也可以不传 ' })
const g: string | number = 1
type myString = string
type obj = { name: string; age: number }
type two = string | number
interface MyObj {
name: string
age: number
}
const h: MyObj = { name: '1', age: 1 }
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
type Animal2 = { name: string }
type Bear2 = Animal2 & { honey: boolean }
const bear2: Bear2 = {
name: 'ww',
honey: true,
}
interface Animal3 {
age: number
}
interface Animal3 {
hobby: number[]
}
const i = document.getElementById('div') as HTMLDivElement
const j = <HTMLDivElement>document.getElementById('div')
const k = 'string' as unknown as number
const l: true = true
const m: 'hello' = 'hello'
const request = (url: string, method: 'GET' | 'POST') => {}
const req = { url: 'www.baidu.com', method: 'POST' as 'POST' }
const req2 = { url: 'www.baidu.com', method: 'POST' } as const
request(req.url, req.method)
request(req2.url, req2.method)
const danger = (x?: number | null) => {
console.log(x!.toFixed())
}
const msg = 'hello'
const tag = Boolean(msg)
const tag2 = !!msg
const msg2 = undefined ?? 'hi'
enum Direction {
UP = 1,
DOWN,
LEFT,
RIGHT,
}
console.log(Direction.UP)
const oneHundred: bigint = BigInt(100)
const name2 = Symbol('ww')
const name3 = Symbol('ww')
type Fish = { swing: () => void }
type Bird = { fly: () => void }
function move(animal: Fish | Bird) {
if ('swing' in animal) animal.swing()
else animal.fly()
}
function logValue(value: Date | string) {
value instanceof Date ? value.toUTCString() : value.toUpperCase
}
logValue(new Date())
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swing !== undefined
}
const isFish2 = (pet: Fish | Bird): pet is Fish => {
return (pet as Fish).swing !== undefined
}
type Shape2 = Fish | Bird
let n: never
const o: string = n
type fn = (a: string) => void
const fn1 = (block: fn) => block('传入String')
fn1((s: string) => {
console.log(s.toUpperCase)
})
type ds = {
description: string
(params: number): boolean
}
const fn2 = (block: ds) => {
block(6)
const d = block.description
}
const block = (params: number) => true
block.description = '111'
fn2(block)
interface CallOrConstructor {
(n: number): Date
new (s: string): Date
}
const date = (d: CallOrConstructor) => {
d(2022)
new d('2022')
}
const firstElement = <T>(arr: T[]): T => arr[0]
function firstElement2<T>(arr: T[]): T {
return arr[0]
}
firstElement([1, 2, 'a'])
firstElement<number | string>([1, 2, 'a'])
const longest = <T extends { length: number }>(a: T, b: T) =>
a.length > b.length ? a : b
longest({ length: 1 }, { length: 2 })
longest([1, 2], [2, 3])
longest('[], string', '有length 属性')
const combine = <T>(a: T[], b: T[]): T[] => a.concat(b)
combine<string | number>([1, 2], ['1'])
function choose(a?: string) {}
function choose2(a: (p?: string) => void) {
a('aaa')
a()
}
choose2(p => p?.toLocaleUpperCase)
function makeDate(t: string): Date
function makeDate(m: number, y: number, d: number): Date
function makeDate(o: string | number, y?: number, d?: number): Date {
return y !== undefined && d !== undefined ? new Date(y, y, d) : new Date(1)
}
function f1(a: any) {
a.b()
}
function f2(a: unknown) {
}
function multiply(n: number, ...m: number[]) {}
multiply(1, 2, 3, 4, 5, 6)
multiply(1, ...[2, 3, 4, 5, 6])
const args = [1, 2] as const
const angle = Math.atan2(...args)
type ABC = { a: number; b: number }
function sum({ a, b }: ABC) {
a + b
}
sum({ a: 1, b: 2 })
function fun(): void {
}
const fun2 = function (): void {
}
type funV = () => void
const fun3: funV = () => true
const fun4: funV = function () {
return true
}
const f5: void = fun3()
interface Shape {
x?: number
y?: number
}
function paintShape({ x = 0, y = 0 }: Shape) {
x + y
}
interface Home {
readonly name: string
readonly person: {
age: number
}
}
interface Person {
age: number
}
interface ReadPerson {
readonly age: number
}
const p: Person = { age: 18 }
const p2: ReadPerson = p
p.age++
interface arrayString {
[i: number]: string
}
const as: arrayString = ['a', 'b']
const as2: arrayString = { 1: 'a' }
interface stringType {
[i: string]: string
x: string
}
const as3: stringType = { name: 'name', x: 'x', y: 'y' }
interface Colorful {
color: string
}
interface Circle {
radius: number
}
interface cAndC extends Colorful, Circle {}
type cAndC2 = Colorful & Circle & { hobby: string }
const cAndC3: Colorful & Circle = { color: 'red', radius: 100 }
const cAndC4: cAndC2 = { color: 'red', radius: 100, hobby: '吃饭' }
interface Box<T> {
content: T
}
const box: Box<string> = {
content: 'cc',
}
type Box2<T> = { content: T }
const box2: Box2<string> = {
content: 'cc',
}
interface Identity<T> {
(arg: T): T
}
const identity: Identity<number> = (arg: number): number => arg
identity(1)
interface Identity2 {
<T>(arg: T): T
}
const identity2: Identity2 = <T>(arg: T): T => {
return arg
}
identity2('1')
class PersonNumber<T> {
age: T
add: (arg: T) => T
}
const pn = new PersonNumber<number>()
pn.age = 1
pn.add = arg => {
return arg
}
pn.add(1)
interface Lengthwise {
length: number
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
arg.length
return arg
}
loggingIdentity('ww')
loggingIdentity([1, 2])
loggingIdentity({ length: 1 })
function getProperty<A, B extends keyof A>(obj: A, key: B) {
return obj[key]
}
getProperty({ name: 'wn', age: 1 }, 'age')
function create<T>(c: { new (): T }): T {
return new c()
}
create(PersonNumber)
function create2<T>(c: new () => T): T {
return new c()
}
create2(PersonNumber)
type Point = { x: number; y: number }
type p = keyof Point
const p1: p = 'x'
const p3: p = 'y'
type ArrayIs = { [i: number]: string }
type A = keyof ArrayIs
const a1: A = 1
type MapIs = { [i: string]: string }
type M = keyof MapIs
const m1: M = 1
const m2: M = 'name'
const obj = {
1: 'number可以为 key',
name: '1',
}
const s = 'hello'
let N: typeof s
N = 'hello'
const msgBox = () => {}
const shouldContinue: typeof msgBox = () => {}
type Predicate = (arg: unknown) => boolean
type K = ReturnType<Predicate>
const myK: K = true
const F = () => {
return { a: 1 }
}
type FF = ReturnType<typeof F>
const ff: FF = { a: 2 }
interface MyPerson {
name: string
age: number
}
type I1 = MyPerson['name']
type I2 = MyPerson[keyof MyPerson]
const key = 'name'
type I3 = MyPerson[typeof key]
interface Animal0 {
(): void
}
interface Animal {
live(): void
live2: () => void
}
const AAAA: Animal0 = () => {}
const AAAA2: Animal = {
live() {},
live2() {},
name: '',
}
type NameOrString<T extends number | string> = T extends number
? number
: string
const createN = <T extends number | string>(arg: T): NameOrString<T> => {
throw ''
}
createN<number>(1)
const NameIs: NameOrString<number> = 1
type Flatten<T> = T extends any[] ? T[number] : T
type str = Flatten<string[]>
type num = Flatten<number>
type GetReturnType<T> = T extends (...arg: any[]) => infer R ? R : never
type NumType = GetReturnType<(x: number, y: string) => number>
const numType: NumType = 1
type ToArray<T> = T extends any ? T[] : never
type SN = ToArray<string | number>
type ToArray2<T> = [T] extends [any] ? T[] : never
type SN2 = ToArray2<string | number>
class PointClass {
name!: string
age = 18
x: number
readonly y: number = 0
constructor() {
this.x = 1
this.y = 1
}
calc() {
this.x + this.y
}
get _x() {
return this.x
}
set _x(value) {
this.x = value
}
}
const pc = new PointClass()
pc._x
pc._x = 100
class Thing {
_size = 0
get size() {
return this._size
}
set size(value: number | string | boolean) {
const num = Number(value)
if (!Number.isFinite(num)) {
this._size = 0
return
}
this._size = num
}
}
const thing = new Thing()
thing.size = 'hh'
class MyClass {
[s: string]: boolean | ((s: string) => boolean)
x = true
check(s: string) {
return this[s] as boolean
}
check2() {
return true
}
}
interface NameCheck {
x?: number
y: number
check(arg: string): boolean
}
class NameCheckClass implements NameCheck {
y = 1
check(s: number | string) {
return true
}
}
class Base {
name = 'base'
constructor() {
console.log('My name is ' + this.name)
}
}
class Derived extends Base {
name = 'derived'
constructor() {
super()
console.log('My name is ' + this.name)
}
}
const der = new Derived()
class MsgError extends Error {
constructor(m: string) {
super(m)
Object.setPrototypeOf(this, MsgError.prototype)
}
}
const msgError = new MsgError('hello')
const isInstance = msgError instanceof MsgError
class AA {
protected x = 10
private y = 10
z = 10
test(a: AA) {
return this.y === a.y
}
}
class BB extends AA {
test2() {
console.log(this.x)
}
}
const bb = new BB()
const aa = new AA()
aa.z
class Box<T> {
content: T
constructor(v: T) {
this.content = v
}
}
const box1 = new Box(1)
class My {
name = 'My'
getName(this: My) {
return this.name
}
}
const my = new My()
my.getName()
const obj1 = {
name: 'obj',
getName: my.getName,
age: 18,
}
const myName = obj1.getName()
const myName2 = my.getName
class Box1 {
a: 1
same(other: this) {}
private c = 2
}
class Derived1 extends Box1 {
b: 1
}
const boxBase = new Box1()
const derived1 = new Derived1()
boxBase.same(derived1)
class Params {
age = 10
constructor(public name: string, age: number) {
this.age = age
}
}
const pa = new Params('ww', 18)
pa.name
pa.age
const Foo = class {}
const foo = new Foo()
abstract class ABClass {
abstract name: string
abstract getName(): string
printName() {}
}
class SunClass extends ABClass {
name = ''
getName(): string {
return ''
}
}
function greet(cons: new () => ABClass) {
const instance = new cons()
}
greet(SunClass)
class Empty {}
function fn(arg: Empty) {}
fn({})
fn(window)
fn(null)
fn(100)
const myNull: null = null
const myUndefined: undefined = undefined
export type cat1 = { name: string }
import { type cat, createName } from '@/note/Test'
const cc: cat = { name: '喵喵' }
createName()
module.exports = {
pi: 3.14,
fn: () => '',
}
exports.fn = () => ''
const maths = require('@/note/Test')
maths.pi
declare const myName: string
declare const jQuery: () => void
jQuery()
declare class Person {
name: string
constructor(name: string)
}
declare module 'lodash' {}
declare module '*.jpg'
declare module '@/utils/index.js'
declare module '*.vue' {}
export namespace time {
export function format() {
return '2022-02-02'
}
}
export namespace price {
export function format() {
return '22.22'
}
}
time.format()
price.format()
泛类约束Partial<T>、Required<T>
Partial<T>:把某个接口类型中定义的属性变成可选
type User = {
id: number
name: string
age: number
}
type UpdatedPerson = Partial<User>
type UpdatedPerson = {
id?: number
name?: string
age?: number
}
Required:把所有可选属性变成必选属性
interface Person {
name?: string;age: number
sex?: string
}
type PersonRequired = Required<Person>
type PersonOptions = {
name: string
sex: string
}