Ts keyPoint
unknown any void never different
(num as unknown as string).split('')
foo(p as unknown){
if(Array.isArray(p)){
return p.length
}
return p.length // error: unknown can't own property
}
foo:()=>void //I don't care the foo return type
// confirm return error or never return
function foo():never {throw new Error('error message')}
function foo():never { while(true){}}
Cumpute
const ref = useRef();
ref.current!.name // confirm have the current property
a?.b?.c // while a isn't null, then a.b
a ?? 10 // while a isn't null or undefined ,then 10 , false '' 0 NaN is true
Operator
interface Person {name: string}
const getValue = (obj: Person , k: keyof Person)=>{
return obj[k]
}
const getValue = (obj: T, k: K)=>{
return obj[k]
}
type typeToNumber{
[k in keyof T]: number // 遍历 traverse
}
type Person {name: string}
typeToNumber(Person) //{name: number}
范型
type Person2 = {
name: string,
age: T
}
const p: Person2 = {
name: 'guolei',
age: 18
}
extends
// 用来约束范性的类型 T:number是不对的因为T是一个类不是变量
function sum(value: T[]): number {
// let count = 0;
// value.forEach(v => count += v);
// return count;
return value.reduce((a,b)=>a+b, 0)
}
infer 变量指代 类似let i = 0
type foo = T extends { t: infer K } ? K : boolean;
const num: foo<{t: number} > = 100;
common unit
interface Person {
name: string
}
const getValue = (obj: Person, k: keyof Person)=>{
return obj[k]
}
type Person2 = {
name: string,
age: T
}
const p: Person2 = {
name: 'guolei',
age: 18
}
function sum(value: T[]): number {
// let count = 0;
// value.forEach(v => count += v);
// return count;
return value.reduce((a,b)=>a+b, 0)
}
type foo = T extends { t: infer K } ? K : boolean;
const num: foo<{ t: number }> = 100;
type Animal = {
name: string,
age: number,
sex?: string
}
type Partial2 = {
[p in keyof T]?: T[p]
}
const particalAnimal: Partial2 = { name: 'xingming' }
type Record2 = {
[p in T]: K
}
const recordAnimal: Record2 = { 'k1': 'k661' }
type Pick2 = {
[p in K]: T[p]
}
const pickAnimal: Pick2 = { name: 'kkkk', age: 100 }
type Exclude2 = T extends K ? never: T
const excludeAnimal: Exclude2 = 'age';
type Omit2 = Pick2>;
const omitAnimal: Omit2 = { sex: 'nan' }
type Require2 = {
[p in keyof T]-?: T[p]
}
const requireAnimal: Require2 = { name: 'k', age: 1232, sex: 'man'}
type ReturnType2 = T extends () => infer K ? K : any;
type foo2 = () => number;
const num2: ReturnType2 = 100