typeScript基础完整版

基础类型

{
  /**
   * @string number Array
   */
  let bol: boolean = false
  let num: number = 6
  let str: string = 'bob'
  let strArr: string[] = ['1', '2', '3']
  let strArr2: Array<string> = ['1', '2', '3']
  /**
   * @元祖 Tuple
   */
  let tup: [string, number] = ['1', 2]
  let tup2: [number, number] = [1, 2]
  // 例 手写useState
  type ArrTup = [number, (nnn: number) => void]
  function useState(n: number): ArrTup {
    let nn = n
    const setN: (nnn: number) => void = nnn => {
      nn = nnn
    }
    return [nn, setN]
  }
  const [initN, setN] = useState(100)
  console.log('initN', initN)
  setN(200)
  console.log('initN', initN)
  /**
   * @枚举 enum
   * 个人理解:一个键值相互对应的对象,可以相互取值,键和值可以任意定义, 但是只有自定的值是number才会产生相对应的键值对
   */
  enum Color {
    red,
    green,
    blue = 4
  }
  // { '0': 'red', '1': 'green', '4': 'blue', red: 0, green: 1, blue: 4 }
  let enu: Color = Color.blue
  console.log('enu', enu) // 4
  let enu2: string = Color[4]
  console.log('enu2', enu2) // 'blue'
  console.log('ColorEnum', Color)
  // 例 场景 当具名参数传递
  enum Gender {
    boy = 1,
    girl = 0
  }
  const getInfo: (people: { gender: number }) => void = () => {}
  getInfo({ gender: Gender.boy })

  /**
   * @任意值 any
   * 两种情况会默认是any 1、定义变量未赋初始值 2、函数的参数未指定类型
   */
  let any: any = 4
  any = 'maybe a string instead'
  any = false
  console.log('any', any) // false
  let anyArr: any[] = ['1', true, 'free']
  anyArr[1] = 100
  console.log('anyArr', anyArr) // ['1', 100, 'free']
  /**
   * @空值 void 从某种意义上只能代表undefined
   *
   */
  let vol = (): void => {}
  let vol2: void = undefined
  /**
   * @null 和 undefined
   */
  let u: undefined = undefined
  let n: null = null
  /**
   * @never 永不存在的值的类型
   */
  function error(message: string): never {
    throw new Error(message)
  }
  function fail() {
    return error('Something failed')
  }
  /**
   * @类型断言
   */
  let someValue: any = 'this is a my understand string'
  let strlength: number = (<string>someValue).length
  console.log('strlength', strlength)
  let someValue2: any = 'this is a my understand string'
  let strlength2: number = (someValue2 as string).length
  /**
   * @类型收窄
   */
  let value = '123'
  if(typeof value === 'string') {
    console.log(value.length);
  }
  /**
   * @联合类型
   */
  let ee: string | number = 1
  let ee2: (string | number)[] = ['1', 2]
  /**
   * @类型别名
   */
  type Nn = string | number
  let ee3: Nn = 1
  let ee4: Nn[] = ['1', 2]
  /**
   * @对象类型
   */
  const obj: {
    name: string
    fn: () => void
  } = {
    name: '张三',
    fn: () => {}
    // fn: function () {}
  }
  type objType = {
    name: string
    age: number
    fn(): void
  }
  const obj2: objType = {
    name: '张三',
    age: 18,
    fn: function () {}
    // fn: () => {}
  }
  // 此处在输入obj的时候会提示出obj中有什么属性
  // console.log(obj2.name)
  /**
   * @字面量类型
   * 一般和联合类型一起使用
   */
  let str1 = '帅哥'
  const str2 = '美女'
  type Direction = 'up' | 'down' | 'left' | 'right'
  function directionFn(params: Direction) {}
  directionFn('down')
  /**
   * @typeof
   */
  const complexObj = {
    name: 'tsmeng',
    age: 18,
    do: () => {},
    love: ['巧克力', '奥利奥']
  }
  type complex = typeof complexObj
  function complexfn(complexObj: complex) {
    complexObj.name
  }
  complexfn(complexObj)
  /**
   * @keyof
   */
  type T = keyof {
    a: 1
    b: 2
    c: 3
  }
  let T1: T = 'a'
}

接口

{
  /**
 * @接口 interface
 */
interface LabelledValue {
  label: string
}
function printLabel (labelledObj: LabelledValue) {
  console.log('labelledObj.label', labelledObj.label)
}
let myObj = { size: 10, label: 'Size 10 Object' }
printLabel(myObj)
/**
 * @可选属性
 */
interface SquareConfig {
  color?: string
  width?: number
}
function createSquare (config: SquareConfig): { color: string; area: number } {
  let newSquare = { color: 'white', area: 100 }
  if (config.color) {
    newSquare.color = config.color
    // newSquare.color = config.colr
    // Error: Property 'clor' does not exist on type 'SquareConfig'
  }
  if (config.width) {
    newSquare.area = config.width * config.width
  }
  return newSquare
}
let mySquare = createSquare({ color: 'black' })
console.log('mySquare', mySquare)
/**
 * @只读属性
 */
interface Point {
  readonly x: number
  readonly y: number
}
let p1: Point = { x: 1, y: 1 }
// p1.x = 2 // 无法为“x”赋值,因为它是只读属性
let a: number[] = [1, 2, 3, 4, 5]
let ro: ReadonlyArray<number> = a
// ro[0] = 2 // 类型“readonly number[]”中的索引签名仅允许读取
// a = ro // 类型 "readonly number[]" 为 "readonly",不能分配给可变类型 "number[]"
a = ro as number[]
console.log('a', a)
/**
 * @额外的属性检查
 */
interface SquareConfig2 {
  color?: string
  width?: number
  // [PropName: string]: any
}
function createSquare2 (config: SquareConfig2): { color: string; area: number } {
  let newSquare = { color: 'white', area: 100 }
  if (config.color) {
    newSquare.color = config.color
  }
  if (config.width) {
    newSquare.area = config.width * config.width
  }
  return newSquare
}

// let mySquare2 = createSquare2({ colour: 'red', width: 100 } as SquareConfig2)
// let mySquare2 = createSquare2({ colour: 'red', width: 100 })
let squareOptions = { colour: 'red', width: 100 }
let mySquare2 = createSquare2(squareOptions)
console.log('mySquare2', mySquare2)
/**
 * @函数类型
 */
interface SearchFunc {
  (source: string, subString: string): boolean
}
let mySearch: SearchFunc = (src: string, sub: string) => {
  let result = src.search(sub)
  return result > -1
}
console.log('mySearch', mySearch('abcdefg', 'f'))
/**
 * @可索引的类型
 */
interface stringArray {
  readonly [index: number]: string
}
const stringArray: stringArray = ['bob', 'jenny']
console.log('stringArray', stringArray[0])
// stringArray[0] = 'bob2' // 类型“stringArray”中的索引签名仅允许读取
/**
 * @继承接口
 */
interface people {
  name: string
  age: number
}
interface p1IF extends people {
  gender: number
}
const p2: p1IF = {
  name: '小明',
  age: 18,
  gender: 1
}
console.log('p2', p2)
/**
 * @混合类型
 */
interface Counter {
  (start: number): string
  interval: number
  reset(): void
}

const getCount = (): Counter => {
  const counter: Counter = start => {
    return String(start)
  }
  counter.interval = 1
  counter.reset = () => {}
  return counter
}
let c = getCount()
console.log('c', c)
console.log('c.interval', c.interval)
console.log('c.reset', c.reset)
}

函数

{
  /**
 * @函数类型
 */
const add = (x: number, y: number): number => {
  return x + y
}
console.log('add', add(1, 2))
// 类型说明 (x: number, y: number) => number
const add2: (x: number, y: number) => number = function (
  x: number,
  y: number
): number {
  return x + y
}
// 类型别名简化
type FnType = (x: number, y: number) => number
const add3: FnType = (x, y) => {
  return x + y
}
console.log('add3', add3(1, 2))
/**
 * @可选参数
 * 可选参数必须跟在必须参数后面
 * 在所有必须参数后面的带默认初始化的参数都是可选的
 * 与普通可选参数不同的是,带默认值的参数不需要放在必须参数的后面。 如果带默认值的参数出现在必须参数前面,用户必须明确的传入undefined值来获得默认值
 */
function buildName (firstName: string = 'Will', lastName?: string) {
  return firstName + ' ' + lastName
}

// let result1 = buildName('Bob') // error, too few parameters
// let result2 = buildName('Bob', 'Adams', 'Sr.') // error, too many parameters
let result3 = buildName('Bob', 'Adams') // okay and returns "Bob Adams"
let result4 = buildName(undefined, 'Adams') // okay and returns "Will Adams"
/**
 * @剩余参数
 */
function buildName2 (firstName: string, ...restOfName: string[]) {
  return firstName + ' ' + restOfName.join(' ')
}

let buildNameFun: (fname: string, ...rest: string[]) => string = buildName2
/**
 * @this
 */
let deck = {
  suits: ['hearts', 'spades', 'clubs', 'diamonds'],
  cards: Array(52),
  createCardPicker: function () {
    // NOTE: the line below is now an arrow function, allowing us to capture 'this' right here
    return () => {
      let pickedCard = Math.floor(Math.random() * 52)
      let pickedSuit = Math.floor(pickedCard / 13)

      return { suit: this.suits[pickedSuit], card: pickedCard % 13 }
    }
  }
}

let cardPicker = deck.createCardPicker()
let pickedCard = cardPicker()

console.log('card: ' + pickedCard.card + ' of ' + pickedCard.suit)
/**
 * @重载
 */
let suits = ['hearts', 'spades', 'clubs', 'diamonds']

function pickCard(x: { suit: string; card: number }[]): number
function pickCard(x: number): { suit: string; card: number }
function pickCard (x): any {
  // Check to see if we're working with an object/array
  // if so, they gave us the deck and we'll pick the card
  if (typeof x == 'object') {
    let pickedCard = Math.floor(Math.random() * x.length)
    return pickedCard
  }
  // Otherwise just let them pick the card
  else if (typeof x == 'number') {
    let pickedSuit = Math.floor(x / 13)
    return { suit: suits[pickedSuit], card: x % 13 }
  }
}

let myDeck = [
  { suit: 'diamonds', card: 2 },
  { suit: 'spades', card: 10 },
  { suit: 'hearts', card: 4 }
]
let pickedCard1 = myDeck[pickCard(myDeck)]
console.log('card: ' + pickedCard1.card + ' of ' + pickedCard1.suit)

let pickedCard2 = pickCard(15)
console.log('card: ' + pickedCard2.card + ' of ' + pickedCard2.suit)

}

泛型

{
  /**
   * @初识
   * @泛型函数 这个函数的参数类型和返回值类型是可变的
   */
  function identity<T>(arg: T): T {
    return arg
  }
  console.log('identity', identity(6))
  /**
   * @泛型数组
   */
  function loggingIdentity<T>(arr: T[]): T[] {
    return arr
  }
  /**
   * @泛型类型
   */
  function identity2<T>(arg: T): T {
    return arg
  }
  let myIdentity2: <T>(arr: T) => T = identity
  /**
   * @泛型接口 接口里的类型是可变的
   */
  interface Identity3 {
    <T>(arg: T): T
  }
  interface Identity4<T> {
    (arg: T): T
  }
  interface Identity5 {
    fn: <T>(arg: T) => T
  }
  let myIdentity3: Identity3 = identity
  let myIdentity4: Identity4<number> = identity
  /**
   * @练习 重构useState
   */
  const useState = <T>(value: T): [T, (newValue: T) => T] => {
    const setState = (newValue: T) => {
      return newValue
    }
    return [value, setState]
  }

  const [s, setS] = useState('1')
  const [n, setN] = useState(1)
  /**
   * @定义只能获取对象已有属性的函数
   */
  const person = {
    name: '张三',
    age: 18
  }
  const getProps = <Obj, Key extends keyof Obj>(obj: Obj, key: Key): any => {
    return obj[key]
  }
  getProps(person, 'name')
}

泛型工具类型

{
  /**
   * @Partial
   */
  type Obj = {
    name: string
    age: number
    like: Array<string>
  }
  type PartialObj = Partial<Obj>
  const obj: PartialObj = {
    name: '王德发'
  }
  /**
   * @Readonly
   */
  type Obj2 = {
    name: string
  }
  type ReadonlyObj = Readonly<Obj2>
  const obj2: ReadonlyObj = {
    name: '王德发'
  }
  // obj2.name = '222'
  /**
   * @Pick
   */
  type Obj3 = {
    name: string
    age: number
    like: Array<string>
  }
  type PickObj = Pick<Obj3, 'name' | 'like'>
  const obj3: PickObj = {
    name: '王德发',
    like: ['1']
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值