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 = <T, K extends keyof T>(obj: T, k: K)=>{
return obj[k]
}
type typeToNumber<T>{
[k in keyof T]: number // 遍歷 traverse
}
type Person {name: string}
typeToNumber(Person) //{name: number}
范型
type Person2 <T> = {
name: string,
age: T
}
const p: Person2<number> = {
name: 'guolei',
age: 18
}
extends
// 用來約束范性的類型 T:number是不對的因為T是一個類不是變量
function sum<T extends number>(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> = 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 <T> = {
name: string,
age: T
}
const p: Person2<number> = {
name: 'guolei',
age: 18
}
function sum<T extends number>(value: T[]): number {
// let count = 0;
// value.forEach(v => count += v);
// return count;
return value.reduce((a,b)=>a+b, 0)
}
type foo<T> = T extends { t: infer K } ? K : boolean;
const num: foo<{ t: number }> = 100;
type Animal = {
name: string,
age: number,
sex?: string
}
type Partial2<T> = {
[p in keyof T]?: T[p]
}
const particalAnimal: Partial2<Animal> = { name: 'xingming' }
type Record2<T extends keyof any, K> = {
[p in T]: K
}
const recordAnimal: Record2<string, string> = { 'k1': 'k661' }
type Pick2<T, K extends keyof T> = {
[p in K]: T[p]
}
const pickAnimal: Pick2<Animal, 'name' | 'age'> = { name: 'kkkk', age: 100 }
type Exclude2<T, K> = T extends K ? never: T
const excludeAnimal: Exclude2<keyof Animal, 'name' | 'sex'> = 'age';
type Omit2<T, K> = Pick2<T, Exclude2<keyof T, K>>;
const omitAnimal: Omit2<Animal, 'name' | 'age'> = { sex: 'nan' }
type Require2<T> = {
[p in keyof T]-?: T[p]
}
const requireAnimal: Require2<Animal> = { name: 'k', age: 1232, sex: 'man'}
type ReturnType2<T> = T extends () => infer K ? K : any;
type foo2 = () => number;
const num2: ReturnType2<foo2> = 100